Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readNext.js
#nextjs#react#usecontext#dependency-resolution
Next.js React duplication diagram with two crate copies feeding one component tree

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:

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.

bash
# 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 dev

If 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:

js
// 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:

bash
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 react
code
my-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 copy

On 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

SymptomUnderlying causeFirst check
Throws on every render, dev and buildtwo copies of reactnpm ls react, pnpm why react
Throws only in next build prerenderstale .next from an older Reactdelete .next, rebuild
Throws only in one workspace packagesymlinked duplicate resolutionnode -p "require.resolve('react')" in that package
Throws only after adding a UI librarylibrary bundles its own Reactcheck the library's peer vs dependency
Throws with "Invalid hook call" in the loghook called outside a componentsearch for top-level use...() calls
Throws when a provider is missingdifferent error text (must be used within)wrap the subtree in the provider
ToolList duplicatesForce one version
npm 8+npm ls reactoverrides in package.json
pnpmpnpm why reactpnpm.overrides in package.json
Yarn (classic)yarn list --pattern reactresolutions in package.json
Yarn Berryyarn why reactresolutions in package.json
Next.js versionReact requirementApp Router notes
14.x18.2+server components stable, React 19 not supported
15.x18.2+ or 19.xReact 19 supported, async params
16.x19.xReact 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" } }
bash
rm -rf node_modules package-lock.json npm install npm ls react # expect exactly one version

Keep 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:

bash
node -p "require.resolve('react')" # in apps/web node -p "require.resolve('react')" # in packages/ui

Two 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.

ts
// 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:

bash
rm -rf .next node_modules/.cache npm run build

In 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:

ts
// 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 call

If 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:

tsx
// 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:

bash
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. react and react-dom must 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 dedupe without an override. It removes duplicates when the ranges allow it and silently keeps two copies when they do not; add overrides for a guaranteed result.
  • Deleting node_modules but 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@19 rendered by react-dom@18 produces this exact stack; npm ls react react-dom is the fastest way to catch it.

Official documentation: Invalid hook call warning and Next.js: React essentials.

Official references

primary documentation

The Next.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.