React useContext Hook

📘 React.js 👁 38 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

The useContext hook allows you to share data across components without passing props manually at every level (also known as prop drilling).


Why useContext?

Without context:

<App> <Header user={user} /> <Main user={user} /> </App>

With context:

  • Data is stored in one place

  • Any component can access it directly


What is Context?

Context provides a way to pass data through the component tree without using props.

Typical use cases:

  • Theme (light/dark)

  • Authentication

  • Language settings

  • Global user data


Basic Steps to Use useContext

1. Create Context

import { createContext } from "react"; export const UserContext = createContext();

2. Provide Context Value

Wrap components with a Provider.

import { UserContext } from "./UserContext"; function App() { const user = { name: "Alice" }; return ( <UserContext.Provider value={user}> <Dashboard /> </UserContext.Provider> ); }

3. Consume Context with useContext

import { useContext } from "react"; import { UserContext } from "./UserContext"; function Dashboard() { const user = useContext(UserContext); return <h1>Welcome, {user.name}</h1>; }

Using Context with State

function App() { const [theme, setTheme] = useState("light"); return ( <ThemeContext.Provider value={{ theme, setTheme }}> <Page /> </ThemeContext.Provider> ); }

Consume it:

const { theme, setTheme } = useContext(ThemeContext);

Default Context Value

const ThemeContext = createContext("light");

Used when no Provider is found.


Updating Context Data

Context values update all consuming components.

<button onClick={() => setTheme("dark")}> Dark Mode </button>

Common Mistakes

❌ Using context for everything
❌ Forgetting to wrap Provider
❌ Storing large, frequently changing data


When to Use useContext

✅ Good for:

  • Global app settings

  • Authentication data

  • Theme and localization

❌ Avoid for:

  • High-frequency updates

  • Deeply complex state logic


Context vs Redux

ContextRedux
Built-inExternal library
Simple global stateComplex state management
Small to medium appsLarge apps

Best Practices

  • Keep context values small

  • Split contexts by responsibility

  • Memoize context values if needed


Key Points

  • useContext avoids prop drilling

  • Works with createContext

  • Provider shares data

  • All consumers re-render on change


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes