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.
How to use the useContext hook in React
Key takeaways
Hooks like
useContextmake 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
useContexthook offers a cleaner and more straightforward solution than Redux. While Redux is powerful for complex apps,useContextworks 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
useContextwith hooks likeuseStateoruseReducer. 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,
useContextcan 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);
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
useContexthook, 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 valueconst CustomThemeContext = createContext("light");function App() {const [backgroundTheme, setBackgroundTheme] = useState("light");return (<CustomThemeContext.Provider value={{backgroundTheme,setBackgroundTheme}}><ChangeTheme /></CustomThemeContext.Provider>);}export default App;
Explanation
Line 1: We import
useStateandcreateContextfrom React.Line 4: We use
createContextto 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
backgroundThemewith an initial value of"light".Line 10: The
CustomThemeContext.Providermakes the theme value (backgroundTheme) and the updater function (setBackgroundTheme) available to all child components. Thevalueprop passes these two variables as an object{backgroundTheme,setBackgroundTheme}.Line 12:
ChangeThemeis a child component wrapped within the provider, meaning it will have access to the context values.
Implement the
useContexthook 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 (<buttononClick={changeTheme}style={{background: backgroundTheme === "light" ? "#fff" : "#555",color: backgroundTheme === "light" ? "#000" : "#fff",}}>Switch to {backgroundTheme === "light" ? "Dark" : "Light"} Theme</button>);}
Explanation
Line 4: We use
useContextto access thebackgroundThemeandsetBackgroundThemeWevalues fromCustomThemeContext. Now, theChangeThemecomponent has access to both the current theme and the function to change it.Lines 6–8: We define a function,
changeThemethat 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
onClickhandler that triggerschangeThemewhen clicked. The button'sstyledynamically sets thebackgroundcolor 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?
Can one component use multiple contexts?
How does useContext affect performance?
How is useContext different from Redux?
Free Resources