0

I was learning about useContext and I get confused and can't really picture a use case for nested providers... Here is an example from React's documentation:

// Theme context, default to light theme
const ThemeContext = React.createContext('light');

// Signed-in user context
const UserContext = React.createContext({
  name: 'Guest',
});

class App extends React.Component {
  render() {
    const {signedInUser, theme} = this.props;

    // App component that provides initial context values
    return (
      <ThemeContext.Provider value={theme}>
        <UserContext.Provider value={signedInUser}>
          <Layout />
        </UserContext.Provider>
      </ThemeContext.Provider>
    );
  }
}

function Layout() {
  return (
    <div>
      <Sidebar />
      <Content />
    </div>
  );
}

// A component may consume multiple contexts
function Content() {
  return (
    **<ThemeContext.Consumer>
      {theme => (
        <UserContext.Consumer>
          {user => (
            <ProfilePage user={user} theme={theme} />
          )}
        </UserContext.Consumer>
      )}
    </ThemeContext.Consumer>**
  );
}

And the explanation about this example that is given in that page is:

To keep context re-rendering fast, React needs to make each context consumer a separate node in the tree. If two or more context values are often used together, you might want to consider creating your own render prop component that provides both.

So speed is the only concern and reason why would we want to create multiple createContext & providers? Is there any other use case for such approach? I guess the biggest question I could ask is why would we need multiple useContext at all... Isn't it universal? I can use it wherever I want in the app. So why would one need second context...

Sol_is_here
  • 110
  • 9
  • 2
    It's just a way to decouple unrelated app state. Having multiple providers means that you can access either of those things. The nesting isn't necessarily important, it's just that there isn't any other way to describe the relationship where two different tags at the same level of the tree have the same children. – Jared Smith Dec 05 '22 at 18:23
  • A change to a state in context rerenders all components that use that context. If you want to have multiple contexts in the tree, you split it to not render all of the components. – Konrad Dec 05 '22 at 18:24

0 Answers0