yaserso
yaserso

Reputation: 2868

Trying to understand React Context

I'm trying to learn what Context is, and here's what I've gathered so far:

How you use it is that whenever you create a Context, you have to use the constant declared to define the contextType in the child components, just to get to use the context.

Here's the example from the official docs:

const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}

The example places all the components in the same file, which allows the developer to use ThemeContext in the ThemedButton class.

I might have App.jsx with the Context created in it, wrapping Home.jsx component with the ThemeContext.Provider, just so I can use it with the ThemedButton down the road. I'll have to do static contextType = ThemeContext in the ThemedButton class in its JSX file, which means I have to import ThemeContext from App.jsx.

From the docs the definition is: Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Can't I do export const theme = 'light' and import it in one of the grandchildren just as well? It is still skipping the parents in the middle and it can go sideways.

Upvotes: 2

Views: 586

Answers (1)

Chaim Friedman
Chaim Friedman

Reputation: 6261

While it is true that you can directly export and import your data, you will lose the benefit of being able to update that data and force a new render. Imagine you are passing a color down via context, along with the color you pass a method which can update the color.

Now you have the option of having some child way down in the tree call this method which changes the color, and have components using this color re-render as a result.

This cannot be done with data living outside of the react world, as would be the case with data you export and import elsewhere.

Upvotes: 4

Related Questions