flashbackzoo
flashbackzoo

Reputation: 358

React getInitialState using props

When setting the initial state of a component, using data passed in via props, should I create a new object, doing something like...

getInitialState: function () {
    return {
        fieldData: JSON.parse(JSON.stringify(this.props.data))
    };
}

or is it safe to just do...

getInitialState: function () {
    return {
        fieldData: this.props.data
    };
}

Upvotes: 10

Views: 15249

Answers (2)

Ashley Coolman
Ashley Coolman

Reputation: 11585

Its been many years since the accepted answer, and I would like to add some points that were possibly not as clear back in 2014:

Props to purely initialise state

It is considered fine to seed state from special initial state props. In the example above, you would have initialFieldData

class Form extends React.Component {
   state = { fieldData: this.props.initialFieldData };
   resetFieldData = () => 
      setState( () => ({ fieldData: this.props.initialFieldData }));

static getDerivedStateFromProps() (docs)

React 16.3-alpha introduced the static function, that allows you to map a your regular props to state (to replace componentWillReceiveProps). A few things to note:

  1. Importantly this is static function: you can't directly access this, but you can access state. In some unusual situations, one might find themselves putting instance values (e.g. refs) into state, just so they can be accessed there.
  2. Runs on mount AND each prop change

Upvotes: 0

Shawn
Shawn

Reputation: 939

Transferring props to the component's state is considered a bad practice: http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

It might be best to consider a different approach. You can access props directly and the component will update when the props are changed.

Upvotes: 7

Related Questions