Loading

Quipoin Menu

Learn • Practice • Grow

react / useContext Hook
tutorial

useContext Hook

Imagine you have a theme (light or dark) that many components in your app need to know about. Passing the theme down through props at every level becomes tedious this is called "prop drilling". React's Context API, together with the `useContext` hook, solves this elegantly.

What is useContext?

`useContext` is a React Hook that lets you read and subscribe to context from your component. It accepts a context object (created by `React.createContext`) and returns the current context value.

Think of Context as a global variable for a subtree of your component tree. Any component inside the provider can access the context without passing props manually.

How to Use useContext

  1. Create a context using `React.createContext()`.
  2. Wrap the component tree with a `` and pass a `value`.
  3. In any child component, call `useContext(Context)` to access that value.

Example: Theme Context
import React, { useContext, useState } from 'react';

<!-- 1. Create a context -->
const ThemeContext = React.createContext();

function App() {
  const [theme, setTheme] = useState('light');

  return (
    <!-- 2. Provide the context value -->
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  return <ThemeButton />;
}

function ThemeButton() {
  <!-- 3. Use the context -->
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <button
      onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
      style={{
        background: theme === 'light' ? '#fff' : '#333',
        color: theme === 'light' ? '#000' : '#fff'
      }}
    >
      Current theme: {theme}
    </button>
  );
}

Example: User Context with Multiple Values
const UserContext = React.createContext();

function App() {
  const [user, setUser] = useState({ name: 'John', loggedIn: true });

  return (
    <UserContext.Provider value={user}>
      <Dashboard />
    </UserContext.Provider>
  );
}

function Dashboard() {
  const user = useContext(UserContext);
  return <h1>Welcome {user.name}!</h1>;
}

When to Use useContext

  • When you have data that many components at different nesting levels need (theme, user authentication, language preferences).
  • To avoid "prop drilling" passing props through intermediate components that don't need them.

Two Minute Drill

  • `useContext` lets you consume a context created by `React.createContext`.
  • You must wrap the component tree with a `` and provide a `value`.
  • Any component inside the provider can call `useContext(Context)` to get the current value.
  • When the context value changes, all components using that context re-render.
  • Use it for global data like themes, user info, or UI state that many components need.

Need more clarification?

Drop us an email at career@quipoinfotech.com