The useContext hook accepts a React context object (the value returned from createContext) and returns the current context value supplied by the nearest <Context.Provider> up the component tree.
flowchart TD
Provider["<UserContext.Provider value={{ user, logout }}>"] --> Tree["Component Hierarchy"]
Tree --> Consumer["const { user } = useContext(UserContext)"]
import React, { createContext, useContext, useState } from 'react';
// 1. Define Context
const AuthContext = createContext(null);
// 2. Auth Provider Component
export function AuthProvider({ children }) {
const [user, setUser] = useState({ name: 'Alex Developer', role: 'Administrator' });
const logout = () => setUser(null);
return (
<AuthContext.Provider value={{ user, logout }}>
{children}
</AuthContext.Provider>
);
}
// 3. Child Component consuming Context via useContext
export function UserProfileHeader() {
const auth = useContext(AuthContext);
if (!auth || !auth.user) {
return <div>Logged Out</div>;
}
return (
<header className="user-header">
<span>Active User: <strong>{auth.user.name}</strong> ({auth.user.role})</span>
<button onClick={auth.logout}>Sign Out</button>
</header>
);
}
useContext() outside a matching Provider tree returns the default context value (or null). Create custom consumer hooks to throw helpful runtime errors.useContext(MyContext) will re-render whenever the value object passed to <MyContext.Provider> changes.Create a custom hook useAuth() that encapsulates useContext(AuthContext) and checks whether the consumer component is properly placed inside <AuthProvider>.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.