Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  89] [ 2]  / answers: 1 / hits: 21263  / 9 Years ago, wed, april 22, 2015, 12:00:00

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.


More From » reactjs

 Answers
15

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.


[#66959] Monday, April 20, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alli

Total Points: 409
Total Questions: 101
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
alli questions
Sat, Apr 23, 22, 00:00, 2 Years ago
Mon, May 18, 20, 00:00, 4 Years ago
Tue, Mar 24, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;