React Context API & The use() Hook
Context API & use() Hook: Pass global properties down the tree and use React 19’s use() hook to read resources directly.
The Context API is React’s built-in mechanism for passing data deep down the component tree without manually threading props through every intermediary layer (the classic "prop drilling" problem).
Historically, reading context meant using the useContext hook or wrapping JSX in consumer render-props. Both approaches were strictly bound by the Rules of Hooks: they could only run unconditionally at the top level of a component.
React 19 overhauls how we interact with Context in two major ways:
- **Direct Provider Syntax:** <Context> can now be rendered directly as a JSX provider without appending .Provider (e.g., <MyContext value="\{...\}">).
- **The use() Hook:** A unified reading primitive that unwraps Context (as well as Promises) conditionally inside loops, if statements, and block scopes.
## 1. Context Boundaries: When (and When Not) to Use It
```text
Context is designed for low-velocity, ambient data that needs to be accessible across broad swathes of the component tree. It is neither a general-purpose state manager nor a server-state cache.
┌────────────────────────┐
│ Application State Type │
└───────────┬────────────┘
│
┌──────────────────────┼──────────────────────┐
▼ ▼ ▼
High-Velocity Server Cache Ambient Globals
(Cart, Video Player) (APIs, DB Records) (Theme, Auth, Locale)
│ │ │
▼ ▼ ▼
Zustand TanStack Query Context API
```
### Ideal Context Use Cases
- **Theming:** Active theme mode ('light' | 'dark'), design system tokens.
- **Authentication & Sessions:** Current user profile, session tokens, tenant IDs, permissions.
- **Internationalization (i18n):** Active locale, formatting rules, translation dictionaries.
- **Compound Components:** Coordinated internal state shared across tightly coupled siblings (e.g., <Tabs>, <TabList>, <TabPanel>).
## 2. Legacy useContext vs. Modern use()
The defining difference between useContext and React 19’s use() is flexibility around call sites:
| Capability | Legacy useContext(ThemeContext) | Modern use(ThemeContext) |
| --- | --- | --- |
| Top-Level Only? | Strictly required (violating throws hook errors) | No (can execute conditionally) |
| Inside if Blocks? | ❌ Forbidden | ✅ Fully supported |
| Inside Loops (for, map)? | ❌ Forbidden | ✅ Fully supported |
| After Early Returns? | ❌ Forbidden | ✅ Fully supported |
| Can Unwrap Promises? | ❌ No (Context only) | ✅ Yes (integrates natively with Suspense) |
## 3. Conditional Context Reading with use()
In earlier React versions, if a component only required context under specific edge cases or feature flags, you were still forced to evaluate useContext on every single render at the top of the file.
With use(), you can defer reading context until the exact branch where it is needed:
```ts
import { createContext, use } from 'react';
interface SecurityContextType {
role: 'admin' | 'moderator' | 'user';
permissions: string[];
}
export const SecurityContext = createContext(null);
interface AdminPanelProps {
showAdministrativeTools: boolean;
}
export function AdminPanel({ showAdministrativeTools }: AdminPanelProps) {
// 1. Guard clause: skip reading context entirely when the flag is false
if (!showAdministrativeTools) {
return
);
}
```
## 4. Simplified Provider Syntax
You no longer need to write .Provider:
```ts
// ❌ Legacy Syntax (React 18 and earlier)
{children}
// ✅ Modern Syntax (React 19+)
{children}
```
- **Note:** ThemeContext.Provider is still supported for backwards compatibility, but <ThemeContext> is the preferred standard going forward.
## 5. Architectural Pattern: Provider & Consumer Pair
To prevent components from rendering outside their required provider—which silently returns undefined or a confusing fallback default—wrap Context in a dedicated provider module with an assertion guard:
```ts
// src/context/AuthContext.tsx
import { createContext, use, useState, type ReactNode } from 'react';
interface User {
id: string;
email: string;
tier: 'free' | 'pro';
}
interface AuthContextValue {
user: User | null;
login: (userData: User) => void;
logout: () => void;
}
// 1. Initialize context to null to catch missing provider boundaries
const AuthContext = createContext(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState(null);
const login = (userData: User) => setUser(userData);
const logout = () => setUser(null);
// Modern direct provider syntax
return (
{children}
);
}
// 2. Encapsulated consumer hook using use()
export function useAuth() {
const context = use(AuthContext);
if (!context) {
throw new Error('useAuth must be consumed within an ');
}
return context;
}
```
## 6. The Context Re-render Problem & Mitigation
Context does not perform selector diffing. When a context value changes, every single component that reads that context via use() or useContext() will re-render, even if it only uses a property that stayed identical:
```text
[ Context Provider: { user: 'Alice', theme: 'dark' } ]
│
┌────────────────┴────────────────┐
▼ ▼
Component A (reads theme) Component B (reads user)
│ │
Theme toggles to 'light' ──► Component B re-renders anyway!
```
- **Strategy 1:** Context Splitting
Split unrelated concerns into dedicated, discrete contexts:
```ts
// ❌ Problematic: Monolithic kitchen-sink context
const AppContext = createContext({ user, theme, cart, notifications });
// ✅ Clean: Discrete, domain-specific contexts
const AuthContext = createContext(user);
const ThemeContext = createContext(theme);
```
Components that only care about theme won't trigger re-renders when user changes.
- **Strategy 2:** Stabilize Provider Values with useMemo
Constructing object literals directly inside the value prop creates a brand-new object reference on every parent render, forcing all consumers to re-render needlessly:
```ts
// ❌ Problematic: Creates a new object reference on EVERY provider render
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState('light');
return (
{children}
);
}
// ✅ Correct: Preserves object identity unless theme changes
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState('light');
const contextValue = useMemo(() => ({
theme,
setTheme,
}), [theme]);
return (
{children}
);
}
```
## 7. Beyond Context: Unwrapping Promises with use()
The use() hook is not limited to Context—it is React 19's general-purpose operator for unwrapping asynchronous resources directly in render.
When passed a Promise, use() suspends the component until that promise resolves, handing off control seamlessly to parent <Suspense> boundaries:
```ts
import { use, Suspense } from 'react';
// Promise created outside the component lifecycle or passed via props
const userPromise = fetch('/api/user/current').then((res) => res.json());
function UserProfile({ dataPromise }: { dataPromise: Promise<{ name: string; email: string }> }) {
// use() suspends the component until dataPromise resolves
const user = use(dataPromise);
return (
);
}
export function App() {
return (
Loading profile...
}>
Standard View Enabled
; } // 2. Conditionally read Context inside an active code branch // This was fundamentally impossible with useContext() const security = use(SecurityContext); if (!security || security.role !== 'admin') { returnAccess Denied: Administrative rights required.
; } return (Admin Capabilities
-
{security.permissions.map((perm) => (
- {perm} ))}
{user.name}
{user.email}
