In react context need help understanding why in react re-renders all consumers every time the Provider re-renders?

29 views Asked by At

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>
    );
  }
}

1

There are 1 answers

2
Nicholas Tower On BEST ANSWER

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.

const one = { something: 'something' };
const two = { something: 'something' };
console.log(one === two);