DEV Community

Karl Castillo
Karl Castillo

Posted on

React: Context

Using useState and useReducer are great but what if you want your state to be accessible through different components? Before, we would've used Redux but now we have React Context.

Context has three parts to it -- creation, provider and consumer.

createContext

We can create a Context using createContext and it takes the initial value you want. This initial value is used when the context has no corresponding value passed to the provider.

const ThemeContext = createContext('light')
Enter fullscreen mode Exit fullscreen mode

<Context.Provider>

The provider allows any descendants of this provider will have access to the current value of the context as well as any changes. The provider accepts a value prop where you can change the current value of the context.

<ThemeContext.Provider>
  ...
</ThemeContext.Provider>
Enter fullscreen mode Exit fullscreen mode

<Context.Consumer>

The consumer is basically the component where you'll have access to the current value of the context. When using this, the children is a render function which receives the current value as an argument.

<ThemeContext.Consumer>
  {value =>
    ...
  }
</ThemeContext.Consumer>
Enter fullscreen mode Exit fullscreen mode

useContext

An alternative way to get the value of a context is to use the hook useContext.

const value = useContext(ThemeContext)
Enter fullscreen mode Exit fullscreen mode

So how do we update the context's value? The context's value can be updated and kept either using useState or useReducer.

// App.js
const [currentTheme, setTheme] = useState('light')
const toggleTheme = () => {
  setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light')
}

const value = {
  theme: currenTheme,
  toggleTheme
}

<ThemeContext.Provider value={value}>
  <Content />
<ThemeContext.Provider value={value}>
Enter fullscreen mode Exit fullscreen mode
// Content.js
const { theme, toggleTheme } = useContext(ThemeContext)
toggleTheme()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)