How to Use the useContext Hook in React
A step-by-step guide on how to create and consume a React Context to share data across components without prop drilling.
Understand the Prop Drilling Problem
Prop drilling happens when you need to pass data from a top-level component down through many intermediate components that do not actually use the data themselves. They only pass it along to reach a deeply nested child. Context solves this by making data available to any component in the tree without manual passing.
Create the Context
Use React.createContext to create a context object. Pass a default value as the argument, which is used when a component consumes the context but has no matching Provider above it in the tree. Store the returned context object in a variable and export it so other components can access it.
Wrap Components with the Provider
The context object comes with a Provider component. Wrap the part of your component tree that needs access to the shared data with this Provider. Pass the actual data you want to share as the value prop on the Provider. Every component inside this Provider can now access that data.
Consume Context with useContext
In any component nested inside the Provider, import useContext from react and import the context object you created. Call useContext and pass the context object as its argument. It returns the current value from the nearest matching Provider above it in the tree.
Update Context Values
To make context values updatable, include a state variable and its setter function in the value you pass to the Provider. Any component that consumes the context receives both the current value and the ability to update it by calling the setter function.
Create a Custom Context Provider
For cleaner code, create a dedicated wrapper component that contains the useState and returns the Provider with the value. Export this wrapper as the Provider component that other files import. This separates the context logic from the rest of the application and makes it easy to manage.
Understand When to Use Context
Context is ideal for data that is considered global within a section of your app, such as the currently logged-in user, theme settings, or language preferences. It is not the right tool for state that changes very frequently, because every component consuming the context re-renders when the value changes.
Avoid Overusing Context
Do not use Context as a replacement for all prop passing. For state that is local to a small part of the component tree, passing props is simpler and more explicit. Reserve Context for genuinely global or widely shared data to keep your components predictable and maintainable.
Ready to master this completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

