268

In React, are there any real differences between these two implementations? Some friends tell me that the FirstComponent is the pattern, but I don't see why. The SecondComponent seems simpler because the render is called only once.

First:

import React, { PropTypes } from 'react'

class FirstComponent extends React.Component {

  state = {
    description: ''
  }

  componentDidMount() {
    const { description} = this.props;
    this.setState({ description });
  }

  render () {
    const {state: { description }} = this;    
    return (
      <input type="text" value={description} /> 
    );
  }
}

export default FirstComponent;

Second:

import React, { PropTypes } from 'react'

class SecondComponent extends React.Component {

  state = {
    description: ''
  }

  constructor (props) => {
    const { description } = props;
    this.state = {description};
  }

  render () {
    const {state: { description }} = this;    
    return (
      <input type="text" value={description} />   
    );
  }
}

export default SecondComponent;

Update: I changed setState() to this.state = {} (thanks joews), However, I still don't see the difference. Is one better than other?

5
  • Hi, thanks for the links, these components are just a sample, but how you link show facebook.github.io/react/tips/… I can set the props into the state if I need this data after ... the question here is about how I when I should store the date from props to my state. Commented Oct 15, 2016 at 20:00
  • 12
    An example - a toggleable component (e.g. a popover or drawer). The parent knows whether the component should start open or closed; the component itself may know whether it is open or not at a point in time. In that case I think this.state = { isVisible: props.isVisible } makes sense. Depends on how the app distributes UI state. Commented Oct 15, 2016 at 20:00
  • 2
    You should read this medium.com/@justintulk/… Commented Nov 27, 2017 at 10:53
  • 5
    In 2017, Facebook demonstrates using props to set initial state in their documentation: reactjs.org/docs/react-component.html#constructor Commented Dec 6, 2017 at 19:30
  • 1
    @Aurora0001 What of in a situation where you need to handle a form, say an edit form that would make network requests on it's own but you need to initialize the inputs with values that would come as props to that component. In order to keep the form dynamic, those values have to be kept in state. Commented Aug 12, 2019 at 0:16

9 Answers 9

235

It should be noted that it is an anti-pattern to copy properties that never change to the state (just access .props directly in that case). If you have a state variable that will change eventually but starts with a value from .props, you don't even need a constructor call - these local variables are initialized after a call to the parent's constructor:

class FirstComponent extends React.Component {
  state = {
    x: this.props.initialX,
    // You can even call functions and class methods:
    y: this.someMethod(this.props.initialY),
  };
}

This is a shorthand equivalent to the answer from @joews below. It seems to only work on more recent versions of es6 transpilers, I have had issues with it on some webpack setups. If this doesn't work for you, you can try adding the babel plugin babel-plugin-transform-class-properties, or you can use the non-shorthand version by @joews below.

Sign up to request clarification or add additional context in comments.

can you explain more how your answer is different from @joews answer?
Added "You can skip the constructor call if all you are doing is setting variables."
If it does not work, you probably need to install this babel plugin "babel-plugin-transform-class-properties".
It isn't an anti-pattern to initialize state from props if it's understood that the state doesn't rely on the props after the initialization. If you are trying to keep the two in sync, that's an anti-pattern.
@ak85 it is the same syntax but you'd use this.state instead. This syntax is just a shorthand syntax for setting the state during the class construction process (and can be used for variables other than state as well)
160

You don't need to call setState in a Component's constructor - it's idiomatic to set this.state directly:

class FirstComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      x: props.initialX
    };
  }
  // ...
}

See React docs - Adding Local State to a Class.

There is no advantage to the first method you describe. It will result in a second update immediately before mounting the component for the first time.

Good answer. It might be worth noting that this is only for setting the initial state; you still need to use setState if you mutate it at any other point, otherwise the changes may not render.
Thanks again jowes, second the documentation facebook.github.io/react/docs/…
On a marginal note: use super(props) in the constructor. Discussion on SO
joews' suggestion works in most cases, but be careful about sending props to this.state directly. Copying props to this.state is actually againt single source of truth (medium.com/react-ecosystem/…). Also, Dan Abramov once suggested not storing props' values in state. (twitter.com/dan_abramov/status/749710501916139520/photo/1).
@Hiroki it's not always. Think about a menu component that could be open or closed. The menu's component could be the source of truth for whether the menu is initially open or closed; the menu itself could be the source of truth as it opens and closes over time.
43

Update for React 16.3 alpha introduced static getDerivedStateFromProps(nextProps, prevState) (docs) as a replacement for componentWillReceiveProps.

getDerivedStateFromProps is invoked after a component is instantiated as well as when it receives new props. It should return an object to update state, or null to indicate that the new props do not require any state updates.

Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. You may want to compare new and previous values if you only want to handle changes.

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

It is static, therefore it does not have direct access to this (however it does have access to prevState, which could store things normally attached to this e.g. refs)

edited to reflect @nerfologist's correction in comments

Just to clarify, it's named getDerivedStateFromProps (mark the capital letter in Props) and the params are nextProps, prevState (not nextState): reactjs.org/docs/…
Wow! we can use this to update state when updated props are received!
Do we still have to create the initial state in the constructor, considering that the getDerivedStateFromProps is always called before the initial rendering ?
26

YOU HAVE TO BE CAREFUL when you initialize state from props in constructor. Even if props changed to new one, the state wouldn't be changed because mount never happen again. So getDerivedStateFromProps exists for that.

class FirstComponent extends React.Component {
    state = {
        description: ""
    };
    
    static getDerivedStateFromProps(nextProps, prevState) {
        if (prevState.description !== nextProps.description) {
          return { description: nextProps.description };
        }
    
        return null;
    }

    render() {
        const {state: {description}} = this;    

        return (
            <input type="text" value={description} /> 
        );
    }
}

Or use key props as a trigger to initialize:

class SecondComponent extends React.Component {
  state = {
    // initialize using props
  };
}
<SecondComponent key={something} ... />

In the code above, if something changed, then SecondComponent will re-mount as a new instance and state will be initialized by props.

Comments

24

You could use the short form like below if you want to add all props to state and retain the same names.

constructor(props) {
    super(props);
    this.state = {
       ...props
    }
    //...
}

it is an anti-pattern to copy properties that never change to the state. It’s better to explicitly describe which fields your component uses.
5

set the state data inside constructor like this

constructor(props) {
    super(props);
    this.state = {
      productdatail: this.props.productdetailProps
    };
}

it will not going to work if u set in side componentDidMount() method through props.

Comments

3

If you directly init state from props, it will shows warning in React 16.5 (5th September 2018)

any idea why it will warn?
It looks like it's only if you use state = props. More info here: github.com/facebook/react/pull/11658#issuecomment-419677176
3

you could use key value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled read this https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

Comments

0

You can use componentWillReceiveProps.

constructor(props) {
    super(props);
    this.state = {
      productdatail: ''
    };
}

componentWillReceiveProps(nextProps){
    this.setState({ productdatail: nextProps.productdetailProps })
}

componentWillReceiveProps is Deprecated can't use for future versions

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.