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.
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.
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.
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;
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
useContexthook in a real world application in this project, Build a Location Tracker Using Leaflet, ReactJS, and Express.js.
useContext hookNow, 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>);}
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 actionLet'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.
Haven’t found what you were looking for? Contact Us
Free Resources