How to Fix: Attempted import error: ‘useContext’ is not exported from ‘react’ (imported as ‘useContext’).

6 min read

That useContext import error in a fresh Next.js build usually points to a React Server Components boundary problem, a broken dependency graph, or a mismatched React/Next.js installation—not to a missing hook in React itself.

If your logs show Attempted import error: 'useContext' is not exported from 'react' (imported as 'useContext') during build, especially in a newly created project, the issue is typically caused by one of a few repeatable conditions: incompatible package versions, corrupted lockfiles or node_modules, client-only code being pulled into a server-only path, or a package resolving React incorrectly.

Understanding the Root Cause

React absolutely exports useContext. So when a build claims it does not, the problem is almost never the hook itself. The error appears when the bundler resolves a module boundary in a way that makes the imported react entry incompatible with the code that expects browser-side hooks.

In current Next.js versions, builds involve a mix of server components, client components, and optimized package resolution. If a dependency or local component uses hooks like useContext, useState, or useEffect without being treated as a client component, the compiler can produce misleading import errors.

The most common technical causes are:

  • Missing 'use client' at the top of a component that uses React hooks.
  • Version mismatch between next, react, and react-dom.
  • Corrupted dependency installation from stale lockfiles or partially upgraded packages.
  • Third-party libraries compiled against a different React expectation and imported into a server-only path.
  • Monorepo or package manager resolution issues causing multiple React copies or the wrong React entrypoint to be bundled.

Another important detail: some builds log this error without failing the process with a non-zero exit code. That usually means the issue is being surfaced during compilation analysis or a non-blocking route build path, but it still indicates something is structurally wrong in the app.

Step-by-Step Solution

Work through these steps in order. In most projects, one of the first three resolves the problem.

1. Verify your package versions

Make sure next, react, and react-dom are aligned.

npm ls next react react-dom

Your package.json should look like this pattern:

"dependencies": {
  "next": "latest",
  "react": "latest",
  "react-dom": "latest"
}

Then reinstall cleanly:

rm -rf node_modules package-lock.json .next
npm install
npm run build

If you use Yarn or pnpm, remove the matching lockfile instead.

2. Add 'use client' to components using hooks

If a component uses useContext directly or indirectly, mark it as a client component.

'use client'

import { useContext } from 'react'
import { ThemeContext } from './theme-context'

export default function Header() {
  const theme = useContext(ThemeContext)
  return <div>{theme}</div>
}

This must be the very first statement in the file. If the component imports another hook-using library, that file may also need to live behind a client boundary.

3. Check parent-child component boundaries

A server component can render a client component, but hook usage must stay inside the client side boundary. For example:

import Header from './Header'

export default async function Page() {
  const data = await fetch('https://example.com/api').then(r => r.json())
  return <Header />
}

And then in Header.tsx:

'use client'

import { useContext } from 'react'

export default function Header() {
  return <div>Client component</div>
}

If you accidentally call a hook in Page without 'use client', the build can fail in confusing ways.

4. Inspect third-party packages importing hooks

If the error points into node_modules, the problem may be a package not marked for client usage or not compatible with your Next.js version. Identify which package is triggering the import.

npm run build

Then search the offending package usage in your app and move it behind a client component wrapper:

'use client'

import SomeProvider from 'some-library'

export default function ClientProvider({ children }) {
  return <SomeProvider>{children}</SomeProvider>
}

Then use that wrapper from a server component layout:

import ClientProvider from './ClientProvider'

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <ClientProvider>{children}</ClientProvider>
      </body>
    </html>
  )
}

5. Ensure React is not duplicated

Multiple installed React versions can produce invalid exports or bad bundler resolution.

npm ls react

If you see more than one version, align them. In a monorepo, also check workspace package peer dependencies. Libraries should usually declare React as a peerDependency, not bundle their own private copy.

6. Reset the project cache completely

Next.js caches aggressively. A stale build artifact can preserve bad module resolution.

rm -rf .next node_modules package-lock.json
npm cache clean --force
npm install
npm run build

7. Test with a minimal client component

Create a tiny isolated file to confirm hook imports work at all.

'use client'

import { useContext, createContext } from 'react'

const DemoContext = createContext('ok')

function DemoInner() {
  const value = useContext(DemoContext)
  return <p>{value}</p>
}

export default function Demo() {
  return (
    <DemoContext.Provider value="ok">
      <DemoInner />
    </DemoContext.Provider>
  )
}

If this builds successfully, the issue is likely tied to a specific third-party package or a server/client boundary deeper in your app.

8. Upgrade or pin to a stable compatible combination

If this appeared in a newly scaffolded app, it may be caused by a temporary ecosystem regression. Try upgrading all core packages first:

npm install next@latest react@latest react-dom@latest

If the issue started after an upgrade, pin known-good versions instead and rebuild. You can also review the official Next.js documentation and React useContext reference to confirm current compatibility patterns.

Common Edge Cases

Using hooks inside app/ layouts without a client wrapper

Layouts are server components by default. If you place a hook-based provider directly in a layout file, you must move that logic into a child file with 'use client'.

Importing a browser-only library in a server component

Some UI libraries use context internally. Even if your file does not call useContext directly, importing that package from a server component can trigger the error.

Transpilation issues in monorepos

If you are importing internal workspace packages, they may not be compiled correctly for Next.js. Ensure the package is either transpiled by Next or published in a compatible format.

Aliased React paths

Custom webpack or tooling aliases that redirect react can break named exports. Remove custom aliases unless absolutely necessary.

Canary or experimental releases

Fresh projects created with cutting-edge versions occasionally expose transient bundler bugs. If everything looks correct but the error persists, test on the latest stable release instead of an experimental channel.

FAQ

Why does React say useContext is not exported when it clearly is?

Because the message is often a symptom of incorrect module resolution, not a literal missing export. Next.js may be treating the file or dependency as part of a server-only graph, or a package mismatch may be causing the wrong React entry to load.

Does adding 'use client' always fix this?

No. It fixes the issue when the real cause is a server/client component boundary. If your project has mismatched package versions, duplicate React copies, or a problematic dependency, you must fix those separately.

Why does the build log the error but not exit with code 1?

Some Next.js compilation paths can surface warnings or route-level errors without immediately failing the overall process, especially during intermediate analysis. Even if the exit code is not fatal, you should still treat the message as a real dependency or component boundary issue.

The practical fix is to verify versions, clean reinstall dependencies, isolate hook usage behind explicit client components, and inspect any third-party package that uses React context internally. In most cases, that eliminates the misleading useContext import error and restores a clean Next.js build.

Leave a Reply

Your email address will not be published. Required fields are marked *