How to use the useContext hook in React

React provides a useContext hook to make it easier to use React Context.

React Context is a powerful state management feature in React. Instead of passing the props down through each component, React Context allows you to broadcast props to the components below.

The useContext hook can be a viable alternative to Redux if your app is simple.

Syntax

const value = useContext(MyContext);
  • MyContext is a context object (the value returned from React.createContext)

The method returns the current value for that context. This value is determined by the value prop of the nearest <MyContext.Provider>, which is above the calling component in the tree.

A component calling useContext will always re-render when the context value changes. You can check out the official documentation for more details.

Code

Let’s create a React Context object to share an app’s theme color across the components.

We will use the createContext hook – the default value is “gray”:

const ThemeContext = React.createContext("gray");

Next, we will use the Context.Provider on the top-level component to provide the theme to all the child components below:

function App() {
  return (
    <ThemeContext.Provider value="gray">
      <ChildComponent />
    </ThemeContext.Provider>
  );
}

Now, the ChildComponent can access or consume the theme context using the useContext hook:

function ChildComponent() {
  const theme = useContext(ThemeContext);
  return (
    <button background: theme, color: theme }}>
      I am styled by theme context!
    </button>
  );
}

Let’s put everything together and see React Context with useContext in action:

import React from 'react';

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Whenever the ThemeContext value changes, the change will be reflected in the consumer child components.

If you’re new to React Hooks or how React Context works, check out our course, The Road to React: The one with Hooks.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved