Henok Tesfaye
Henok Tesfaye

Reputation: 9560

React context provider and consumer

ThemeContext.js

import React from 'react';

const ThemeContext = React.createContext(null);

export default ThemeContext;

Parent component

import ThemeContext from './ThemeContext';

class A extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value={'green'}>
        <D />
      </ThemeContext.Provider>
    );
  }
}

Component C is below component D.

import ThemeContext from './ThemeContext';

class C extends React.Component {
  render() {
    return (
      <ThemeContext.Consumer>
        {coloredTheme =>
          <div style={{ color: coloredTheme }}>
            Hello World
          </div>
        }
      </ThemeContext.Consumer>
    );
  }
}

What makes me vague is that we are importing "ThemeContext.js" from the provider(component A) and the consumer(component C). So how could the two components share a single ThemeContext instance( how does the consumer access the providers context without sharing a single one) , both have their own ThemeContext?

Upvotes: 8

Views: 4110

Answers (1)

Estus Flask
Estus Flask

Reputation: 222334

It is the relationship between Provider parent and Consumer descendants that allows to share values between them.

<ThemeContext.Consumer> in C has <ThemeContext.Provider value={'green'}> as parent, so it's able to access green context value as coloredTheme callback parameter.

both have their own ThemeContext?

ES modules are evaluated once and result in singletons. ThemeContext is context object. It is same in A and C modules.

Upvotes: 6

Related Questions