Next.js: Cannot read properties of null (reading 'useContext')
A null useContext crash in Next.js usually means two copies of React in node_modules. Deduplicate the versions, clear .next, and verify the resolution.

Introduction & Quick Summary
The dev server compiles, then the page dies with a stack trace whose first frame is inside React's internals rather than your code:
TypeError: Cannot read properties of null (reading 'useContext')
at Object.useContext (node_modules/next/dist/compiled/react/cjs/react.development.js:1584:19)
at MyHeader (components/MyHeader.tsx:8:20)Quick answer: the component is reading React's internal context object, and that object is null because the React instance rendering it is not the React instance your component imported. In Next.js this is almost always two copies of react in node_modules, or versions of react and react-dom that do not match the ones next was built against. Align and dedupe the versions, then clear the build cache.
# 1. see whether more than one React exists
npm ls react react-dom
# or: pnpm why react
# 2. align versions and remove the duplicate
npm install react@latest react-dom@latest
npm dedupe
rm -rf node_modules/.next .next
npm run devIf they were already aligned, the cause is usually a stale .next cache from an older React, a monorepo that resolves react twice through symlinks, or a hook called at module scope — each with a distinct fingerprint.
Core Mechanics, Signatures & Reproducible Setup
Next.js ships its own compiled copy of React (next/dist/compiled/react) for rendering on the server and for some internal components. Your components import react and react-dom from node_modules. Normally those resolve to the same version and React's internal shared state — the dispatcher that useContext, useState and friends read — is initialized once per render.
When two copies are loaded, one copy owns the shared state and the other sees null:
// react.development.js (simplified)
function useContext(Context) {
const dispatcher = ReactSharedInternals.A; // null outside a matching render
return dispatcher.useContext(Context);
}dispatcher is null when the owning React never started a render for this copy, so the very next property read throws. Nothing is wrong with your context provider; the failure is at the module-resolution layer.
A minimal reproduction with npm:
npm init -y
npm install next@15 react@18 react-dom@18
npm install some-ui-lib@latest # a library that pins react@19 as a dependency
npm ls reactmy-app@1.0.0
├─┬ next@15.5.0
│ └── react@18.3.1
├─┬ react@18.3.1
└─┬ some-ui-lib@2.0.0
└── react@19.0.0 <-- second copyOn the server the page renders with Next's copy and the library's copy throws on the first hook. The same tree in a browser bundle can fail only on hydration, which is why the error sometimes appears after the page has painted.
next declares react and react-dom as peer dependencies, so versions must satisfy its range. For the App Router, Next 14 and 15 expect React 18.2+, Next 15 supports React 19 as well, and Next 16 requires React 19. A mismatch inside a workspace is not an install error — npm happily installs both — and the failure surfaces only at render time.
Key Comparison Table
| Symptom | Underlying cause | First check |
|---|---|---|
| Throws on every render, dev and build | two copies of react | npm ls react, pnpm why react |
Throws only in next build prerender | stale .next from an older React | delete .next, rebuild |
| Throws only in one workspace package | symlinked duplicate resolution | node -p "require.resolve('react')" in that package |
| Throws only after adding a UI library | library bundles its own React | check the library's peer vs dependency |
| Throws with "Invalid hook call" in the log | hook called outside a component | search for top-level use...() calls |
| Throws when a provider is missing | different error text (must be used within) | wrap the subtree in the provider |
| Tool | List duplicates | Force one version |
|---|---|---|
| npm 8+ | npm ls react | overrides in package.json |
| pnpm | pnpm why react | pnpm.overrides in package.json |
| Yarn (classic) | yarn list --pattern react | resolutions in package.json |
| Yarn Berry | yarn why react | resolutions in package.json |
| Next.js version | React requirement | App Router notes |
|---|---|---|
| 14.x | 18.2+ | server components stable, React 19 not supported |
| 15.x | 18.2+ or 19.x | React 19 supported, async params |
| 16.x | 19.x | React 19 required, Turbopack default |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Pinning one React with overrides
Once npm ls react shows a nested copy, force the root version. npm 8 and later reads overrides at the project root, pnpm reads pnpm.overrides, Yarn classic reads resolutions:
{
"dependencies": {
"next": "15.5.0",
"react": "19.2.0",
"react-dom": "19.2.0"
},
"overrides": {
"react": "19.2.0",
"react-dom": "19.2.0"
}
}rm -rf node_modules package-lock.json
npm install
npm ls react # expect exactly one versionKeep react and react-dom on the identical version string: React refuses to render when the two packages disagree, and a half-upgraded pair produces the same useContext crash in a less obvious place.
2. Workspaces and symlinked packages
In a monorepo, packages/ui can resolve react from its own node_modules while apps/web resolves the hoisted one. Check the actual path from each package rather than trusting the lockfile:
node -p "require.resolve('react')" # in apps/web
node -p "require.resolve('react')" # in packages/uiTwo different paths mean two React instances. Fix it by declaring React as a peerDependency in the library package, adding it to transpilePackages in next.config.ts so Next compiles the workspace source with its own settings, and letting the workspace tool hoist a single copy.
// next.config.ts
import type { NextConfig } from "next";
const config: NextConfig = {
transpilePackages: ["@acme/ui"],
outputFileTracingRoot: path.join(__dirname, "../../"),
};
export default config;3. Stale .next and Turbopack caches
A build created with React 18 keeps the old module ids after you upgrade to 19, and the dev server can serve a mix of both. The fingerprint is an error that appears only in one mode (usually next build) and disappears after a clean:
rm -rf .next node_modules/.cache
npm run buildIn Docker builds the same problem shows up when the deps stage installs one version and the builder stage copies a .next directory produced earlier; copy node_modules and .next from the same stage, or rebuild both.
4. Hooks at module scope look similar but are not
Calling a hook outside a component fails earlier with React's own warning, and the two are easy to confuse when a barrel file hides the call:
// components/useLocale.ts — wrong: runs when the module is imported
import { useContext } from "react";
import { LocaleContext } from "./locale-context";
export const locale = useContext(LocaleContext); // Invalid hook callIf the console shows Invalid hook call. Hooks can only be called inside of the body of a function component next to the null read, the duplicate-copy fix is not your problem: move the call into a component or a custom hook.
5. Providers must be client components
In the App Router a context provider is a client-side feature. A provider file without 'use client' is compiled as a server component, and the consumer receives an uninitialized context:
// components/theme-provider.tsx
"use client";
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext<"light" | "dark">("light");
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme] = useState<"light" | "dark">("dark");
return <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>;
}
export const useTheme = () => useContext(ThemeContext);Then wrap the subtree in the root layout. Server components can render client providers; they cannot consume them.
6. Confirm the fix with the resolution, not the page
After the change, verify the single copy before reloading anything. A page that happens to render is weaker evidence than a lockfile that resolves one React:
npm ls react react-dom --all | grep -c "react@" # expect a small, known number
node -e "console.log(require('react').version, require('react-dom').version)"When both commands report the same version and the error persists, the remaining candidate is a library that bundles React into its own dist file rather than importing it; check its README for a peer-dependency build or an alias. Comparing two lockfile resolutions line by line is faster with the text diff tool, and reading the resolved tree is easier with the JSON formatter.
Common Compilation/Runtime Mistakes & Version Gotchas
- Upgrading only
react.reactandreact-dommust match exactly; a mixed pair throws inside the renderer before your component runs. - Blaming the provider. The error text mentions
useContext, so people wrap more providers; the null is React's dispatcher, not your context value. npm dedupewithout an override. It removes duplicates when the ranges allow it and silently keeps two copies when they do not; addoverridesfor a guaranteed result.- Deleting
node_modulesbut not the lockfile. A stale lockfile reinstalls the same duplicate tree; remove both or run the package manager's update command. - Assuming the error is a server-only problem. The same two copies fail during hydration in the browser, usually reported as a hydration mismatch plus the null read.
- Version notes. Next 16 requires React 19 and fails earlier with a peer-dependency error, so the null read mostly appears on Next 14/15. React 19 moved some internals, and
react@19rendered byreact-dom@18produces this exact stack;npm ls react react-domis the fastest way to catch it.
Official documentation: Invalid hook call warning and Next.js: React essentials.
Official references
primary documentationThe Next.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesModule not found: Can't resolve a package or alias in Next.js
TypeScript and the bundler resolve imports separately. Align path aliases, workspace dependencies, exports conditions and filename case.
Next.js 16 DynamicServerError: cookies(), headers() and fetchCache
Request-time APIs make a route dynamic, and Next 16 replaced the segment configs with Suspense boundaries and use cache. What to delete and what to wrap.
Next.js cacheComponents: 'used uncached or runtime data' build error
Cache Components makes the build refuse to guess where the static shell ends. Stream it, cache it with use cache, or declare the route blocking.
next/font: Failed to fetch a Google font during the build
The font is fetched during the build, not at runtime. Vendor it with next/font/local or give CI and Docker a route out.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.