[javascript] React component initialize state from props

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?

This question is related to javascript reactjs components

The answer is


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


You can use componentWillReceiveProps.

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

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

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


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


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.


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.


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
    }
    //...
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to components

How to Refresh a Component in Angular Angular 4 - get input value Disable Button in Angular 2 How to Pass data from child to parent component Angular How to map an array of objects in React Checking for Undefined In React What's the difference between an Angular component and module React component initialize state from props How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime React - how to pass state to another component