Understanding when to use Context
Before diving into learning the way to combine Context and Subscription, let's recap how Context works.
The following is a simple Context example with a theme. So, we specify a default value for createContext
:
const ThemeContext = createContext("light"); const Component = () => { const theme = useContext(ThemeContext); return <div>Theme: {theme}</div> };
What useContext(ThemeContext)
returns depends on the Context in the component tree.
To change the Context value, we use a Provider
component in Context as follows:
<ThemeContext.Provider value="dark"> <Component /> </ThemeContext.Provider>
In this case, Component
will show the theme as dark
.
The provider can be nested. It will use the value from the innermost provider:
<ThemeContext.Provider value="this value is not used"> <ThemeContext.Provider value...