Global State with useContext & Reusable Custom Hooks
As frontend applications grow in scale, sharing state across deeply nested component hierarchies becomes a major architectural challenge. Passing props through multiple intermediate components that do not need them—an anti-pattern known as prop drilling—creates tightly coupled, fragile codebases. In modern React, this is solved through the Context API combined with Custom Hooks. In this lesson, we master global state management, context providers, and abstracting business logic into reusable custom hooks.
The Problem of Prop Drilling
Imagine an authenticated user session: the currentUser object is fetched at the root App component but required deep down inside an AvatarMenu component nested four levels below (App -> Header -> Navigation -> UserSection -> AvatarMenu). Forcing intermediate components like Navigation and UserSection to receive and forward currentUser clutters their interface contracts with state they never utilize.
The Three Pillars of React Context
The React Context API enables state to be broadcast globally across a component subtree without intermediate prop forwarding:
createContext(): Defines the context object holding default fallback data:const AuthContext = createContext(null);.<Context.Provider>: A wrapper component that supplies the current context value to all child components nested within its JSX subtree:<AuthContext.Provider value={{ user, login, logout }}>{children}</AuthContext.Provider>.useContext(): A hook invoked by any descending component to read the current context value directly, bypassing intermediate layers.
Performance: Preventing Context Re-Render Cascades
A crucial caveat of React Context is that whenever a provider's value reference changes, every consumer component subscribing to that context is forced to re-render. To avoid accidental re-render cascades, always memoize provider values using useMemo and useCallback:
const providerValue = useMemo(() => ({
user,
token,
isAuthenticated: Boolean(user)
}), [user, token]);
return <AuthContext.Provider value={providerValue}>{children}</AuthContext.Provider>;
Architecting Reusable Custom Hooks
A Custom Hook is a standard JavaScript function whose name begins with the word use and that can invoke other built-in React hooks (like useState, useEffect, or useContext). Custom hooks allow you to decouple complex stateful logic (such as data fetching, form validation, or browser event listeners) from visual UI rendering:
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let isCancelled = false;
setLoading(true);
fetch(url)
.then(res => res.json())
.then(json => {
if (!isCancelled) {
setData(json);
setLoading(false);
}
})
.catch(err => {
if (!isCancelled) {
setError(err);
setLoading(false);
}
});
return () => { isCancelled = true; };
}, [url]);
return { data, loading, error };
}
The Rules of Hooks
To ensure React can reliably associate state calls with specific components across renders, you must adhere to two golden rules enforced by the ESLint react-hooks/rules-of-hooks plugin:
- Only Call Hooks at the Top Level: Never invoke hooks inside loops, conditional statements, or nested functions.
- Only Call Hooks from React Functions: Invoke hooks strictly from React functional components or custom hooks.
When to Migrate to External State Libraries
While React Context is ideal for low-frequency global state (such as themes, language locales, or authenticated user profiles), high-frequency updates (such as real-time chat feeds or interactive graphics) can degrade rendering performance. For high-frequency state, consider external state libraries like Zustand, Redux Toolkit, or Jotai.
Custom Hook Testing Strategies
Because custom hooks encapsulate state logic without visual markup, they can be tested independently of specific UI components using testing utilities like @testing-library/react-hooks. The renderHook() helper mounts hooks in an isolated test harness, allowing engineers to assert state updates, asynchronous promises, and cleanup lifecycles in automated CI/CD pipelines.
import React, { createContext, useContext, useState, useEffect } from 'react';
// 1. Create Theme Context
const ThemeContext = createContext({ theme: 'light', toggleTheme: () => {} });
// 2. Custom Hook encapsulating Window Width detection
function useWindowWidth() {
const [width, setWidth] = useState(typeof window !== 'undefined' ? window.innerWidth : 1200);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
// 3. Consumer Component
export default function ThemeConsumer() {
const { theme, toggleTheme } = useContext(ThemeContext);
const windowWidth = useWindowWidth();
return (
<div style={{ padding: '20px', background: theme === 'dark' ? '#0f172a' : '#f8fafc', color: theme === 'dark' ? '#fff' : '#000' }}>
<h4>Theme: {theme} | Viewport: {windowWidth}px</h4>
<button onClick={toggleTheme}>Toggle Theme Mode</button>
</div>
);
}