React component initialize state from props React component initialize state from props javascript javascript

React component initialize state from props


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.


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.


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