DEV Community


React: Context

koralarts profile image Karl Castillo ・1 min read

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.


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')


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.



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.

  {value =>


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

const value = useContext(ThemeContext)

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,

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


Editor guide