Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is good practice to pass state as props to children?

Tags:

I find myself aggregating the state on one component. Normally the node I know I will re-render so changes can propagate and state is not all over the place. Lately, I've found myself passing the state of this component as props to its first children using JSX spread attributes for the most part. Just to be absolutely clear, this is what I mean:

var Child = React.createClass({
  handleClick: function(){
    this.props.owner.setState({
      count: this.props.count + 1,
    });
  },
  render: function(){
    return <div onClick={this.handleClick}>{this.props.count}</div>;
  }  
});

var Parent = React.createClass({
  getInitialState: function(){
    return {
      count: 0,
      owner: this
    };
  },
  render: function(){
    return <Child {...this.state}/>
  }
});

And it works (http://jsbin.com/xugurugebu/edit?html,js,output), you can always go back to this component to understand whats going on and keep state as minimal as possible.

So the actual question is, if that is/isn't a good practice and why.

The downside I can think about at the moment is that with this approach maybe every child component would always re-render when there is a state change on the owner, if that's the case I think the above is something to use on small Component trees.

like image 832
stringparser Avatar asked Apr 22 '15 11:04

stringparser


People also ask

Should you pass state as props?

Passing state as props from parent to child components is a core concept of React. By keeping state in only a few components and passing it to as many children as needed in the form of props, you will be able to write code that is easier to maintain, and you will thank yourself down the road.

What is the children prop and why is it useful?

The React children prop is an important concept for creating reusable components because it allows components to be constructed together. However, a common issue with using React with Typescript is figuring out which data type to use with React children since Typescript is a strongly typed library.


1 Answers

Yes!

State should only be set on the top level element, this ensures that data only ever flows one way through your components.

Bear in mind, React will only render the changes that have been made since the last render, if parts of your child elements haven't been modified they will not be re-rendered to the DOM.

React has a section in their docs titled lifting up state.

like image 50
Kristian Roebuck Avatar answered Sep 20 '22 11:09

Kristian Roebuck