Shashi
Shashi

Reputation: 341

React context how it works

Learning React , and curious to know how the the below way of consuming context works behind the scenes?

  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}

How does this.context gets setup automatically by declaring static contextType ?

Upvotes: 1

Views: 561

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84922

The code that handles this can be found here: https://github.com/facebook/react/blob/master/packages/react-reconciler/src/ReactFiberClassComponent.new.js#L531

In short, they check if ctor.contextType exists (where ctor is the constructor for the component). If it does, they read what the value in context is, and then call the constructor with that value.

const contextType = ctor.contextType;
//...
if (typeof contextType === 'object' && contextType !== null) {
    context = readContext((contextType: any));
}
//...
const instance = new ctor(props, context);

Upvotes: 2

Related Questions