What is useContext in React: Simple Explanation and Example
useContext is a React hook that lets you share data between components without passing props manually at every level. It accesses the value from a Context object, making it easier to manage global or shared state.How It Works
Imagine you have a family recipe book that everyone in your family can use without asking each other every time. In React, useContext works like that recipe book. Instead of passing information down through many layers of components (like telling each family member the recipe), you create a shared place called a Context. Components can then directly read or update the shared data from this place.
This avoids the hassle of passing props through many components that don't need the data themselves but only pass it along. It makes your code cleaner and easier to maintain, especially when many components need the same information.
Example
This example shows how to create a context for a theme color and use useContext to access it in a child component.
import React, { createContext, useContext } from 'react'; // Create a Context with default value const ThemeContext = createContext('light'); function DisplayTheme() { // Access the current theme value const theme = useContext(ThemeContext); return <p>The current theme is: <strong>{theme}</strong></p>; } export default function App() { return ( // Provide the theme value to children <ThemeContext.Provider value="dark"> <DisplayTheme /> </ThemeContext.Provider> ); }
When to Use
Use useContext when you have data or state that many components need to access or update, such as user info, theme settings, or language preferences. It helps avoid "prop drilling," which is passing props through components that don't use them just to reach deeper components.
For example, if you build a website with a dark mode toggle, you can store the current mode in a context and let any component read or change it easily. This makes your app simpler and more organized.
Key Points
- useContext reads data from a React Context.
- It avoids passing props through many layers.
- Works well for global or shared state like themes or user info.
- Requires a Context Provider to supply the data.
- Helps keep components clean and focused.
Key Takeaways
useContext lets components share data without prop drilling.useContext inside a Context Provider.