Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between state and props in React?

I was watching a Pluralsight course on React and the instructor stated that props should not be changed. I'm now reading an article (uberVU/react-guide) on props vs. state and it says

Both props and state changes trigger a render update.

Later in the article it says:

Props (short for properties) are a Component's configuration, its options if you may. They are received from above and immutable.

  • So props can change but they should be immutable?
  • When should you use props and when should you use state?
  • If you have data that a React component needs, should it be passed through props or setup in the React component via getInitialState?
like image 336
iamdtang Avatar asked Jan 16 '15 19:01

iamdtang


People also ask

Should I use state or props React?

Both state and props in react are used to control data into a component, generally props are set by parent and passed to child components and they are fixed throughout the component. For data that is going to change, we have to use state.

What is prop in React?

Props are arguments passed into React components. Props are passed to components via HTML attributes. props stands for properties.

Are props immutable?

Props are immutable, while state is mutable Although a component is not allowed to change its props, it is responsible for the props of its child components down the component tree. On the other hand, state is mutable.


1 Answers

Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child within the render method of the parent as the second argument to React.createElement() or, if you're using JSX, the more familiar tag attributes.

<MyChild name={this.state.childsName} /> 

The parent's state value of childsName becomes the child's this.props.name. From the child's perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:

this.setState({ childsName: 'New name' }); 

and React will propagate it to the child for you. A natural follow-on question is: what if the child needs to change its name prop? This is usually done through child events and parent callbacks. The child might expose an event called, for example, onNameChanged. The parent would then subscribe to the event by passing a callback handler.

<MyChild name={this.state.childsName} onNameChanged={this.handleName} /> 

The child would pass its requested new name as an argument to the event callback by calling, e.g., this.props.onNameChanged('New name'), and the parent would use the name in the event handler to update its state.

handleName: function(newName) {    this.setState({ childsName: newName }); } 
like image 108
Todd Avatar answered Sep 21 '22 00:09

Todd