Why is this happening? I am trying to understand why putting the object {something:'something'} directly in value re-renders the consumers.
https://reactjs.org/docs/context.html
Before:
class App extends React.Component {
render() {
return (
<Provider value={{something: 'something'}}>
<Toolbar />
</Provider>
);
}
}
After:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: {something: 'something'},
};
}
render() {
return (
<Provider value={this.state.value}>
<Toolbar />
</Provider>
);
}
}
It's because every time App rerenders, a brand new object is created and passed in as the value. That new object may have the same properties as before, but it's still a new object. The provider uses an object reference comparison to tell whether or not the value has changed (ie, it compares with
===). Since the references are different, it is considered to have changed and the subscribers must rerender with this new value.