Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React getInitialState using props

Tags:

reactjs

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
    };
}
like image 418
flashbackzoo Avatar asked Dec 09 '14 10:12

flashbackzoo


Video Answer


1 Answers

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.

like image 85
Shawn Avatar answered Nov 09 '22 19:11

Shawn