How to use the useContext hook in React

Key takeaways

  • Hooks like useContext make it easier to manage the global state across components without prop drilling. This makes it easier to share data like themes or user states across components, streamlining your code and improving maintainability.

  • For apps with simpler state management needs, the useContext hook offers a cleaner and more straightforward solution than Redux. While Redux is powerful for complex apps, useContext works well when state updates are limited to a few components or involve only a handful of global variables.

  • Context values can change dynamically by combining useContext with hooks like useState or useReducer. This allows you to create responsive components that update based on user interactions or external data changes, like toggling between light and dark themes.

  • When overused, useContext can lead to performance bottlenecks, as every change in context triggers a re-render of all consuming components.

What is the useContext hook?

The useContext hook in React provides access to the global state across components without prop drilling. Additionally, it can act as a more lightweight alternative to Redux for simple state management tasks.

The syntax to define it is as follows:

const value = useContext(Context);
useContext hook syntax

Here, Context is the context object you create using createContext. The useContext hook will return the value provided by the nearest Context.Provider in the component hierarchy. If no provider is found, the returned value will be the defaultValue you have passed to createContext for that context. Each time the context value changes, components consuming it re-render automatically. This helps keep the UI synchronized with the latest state.

Learn more the useContext hook, by trying this project, Markdown Editor Application in React Using Context APIs and Hooks.

Creating and providing context

Let's build an app that uses a context to switch between light and dark themes. The theme value will be managed using React’s useState hook.

import React, { createContext, useState } from 'react';
// Create context with a default value
const CustomThemeContext = createContext("light");
function App() {
const [backgroundTheme, setBackgroundTheme] = useState("light");
return (
<CustomThemeContext.Provider value={{backgroundTheme,setBackgroundTheme}}>
<ChangeTheme />
</CustomThemeContext.Provider>
);
}
export default App;
Creating and providing context

Explanation

  • Line 1: We import useState and createContext from React.

  • Line 4: We use createContext to create a new context object, CustomThemeContext. We provide "light" as the default value. If no <Provider> is found above in the component tree, this value will be used when a component consumes the context.

  • Line 7: We declare a state variable called backgroundTheme with an initial value of "light".

  • Line 10: The CustomThemeContext.Provider makes the theme value (backgroundTheme) and the updater function (setBackgroundTheme) available to all child components. The value prop passes these two variables as an object {backgroundTheme,setBackgroundTheme}.

  • Line 12: ChangeTheme is a child component wrapped within the provider, meaning it will have access to the context values.

Implement the useContext hook in a real world application in this project, Build a Location Tracker Using Leaflet, ReactJS, and Express.js.

Consuming context with the useContext hook

Now, let’s create a component that consumes the theme context and allows users to toggle between themes.

import React, { useContext } from 'react';
function ChangeTheme() {
const { backgroundTheme, setBackgroundTheme } = useContext(CustomThemeContext);
function changeTheme() {
setBackgroundTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
};
return (
<button
onClick={changeTheme}
style={{
background: backgroundTheme === "light" ? "#fff" : "#555",
color: backgroundTheme === "light" ? "#000" : "#fff",
}}
>
Switch to {backgroundTheme === "light" ? "Dark" : "Light"} Theme
</button>
);
}
Consuming context with the useContext hook

Explanation

  • Line 4: We use useContext to access the backgroundTheme and setBackgroundThemeWe values from CustomThemeContext. Now, the ChangeTheme component has access to both the current theme and the function to change it.

  • Lines 6–8: We define a function, changeTheme that checks the current theme, prevTheme. If the theme is "light", it switches it to "dark", and vice versa.

  • Lines 11–19: We render a button with an onClick handler that triggers changeTheme when clicked. The button's style dynamically sets the background color based on the current theme. The button text shows the target theme (e.g., “Switch to Dark Theme” if the current theme is light).

Explore hooks in React with the help of this project, Create a Trello Clone with React.

useContext in action

Let's look at a working example by combining everything and executing the application.

The useContext hook simplifies state management by removing the need for prop drilling and makes your code cleaner. However, it’s important to handle context updates carefully to avoid performance issues. When used effectively, the useContext hook can greatly enhance the organization and scalability of your React applications.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


When should I use the useContext hook?

Use the useContext hook when there is a need to share states or functions between components without passing them as props. For example, sharing user data or managing themes across components.


Can one component use multiple contexts?

Yes, a single component can use multiple contexts. This is done by simply calling useContext for each context.


How does useContext affect performance?

Each time the value of a context changes, every component consuming it will re-render. This can affect the overall performance as the components are re-rendered often. To mitigate this, consider splitting contexts for different state slices, memoizing components with React.memo, or using libraries like React-Redux for optimized state updates.


How is useContext different from Redux?

The useContext hook is simpler and built into React, making it ideal for small-scale state management like themes or user authentication. Redux, however, is better for complex applications, offering tools like Redux DevTools for debugging. While useContext is quick to implement, Redux provides more scalability and optimized state updates for larger apps.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved