Fix TypeError: Cannot read properties of null (reading 'useState') in React
This error occurs when React hooks are called outside a component or when multiple copies of React exist in the bundle. Common causes include calling useState in a regular function, having mismatched React versions, or incorrect bundler configuration. Fix it by ensuring hooks are only called inside React function components.
Reading the Stack Trace
Here's what each line means:
- at useState (node_modules/react/cjs/react.development.js:1622:21): React's internal dispatcher is null, meaning useState was called outside the React rendering lifecycle.
- at Counter (/app/src/components/Counter.tsx:4:35): The Counter component at line 4 calls useState, but React's internal state is not initialized for this call.
- at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:16305:18): React's hook system failed to initialize properly, possibly due to duplicate React instances.
Common Causes
1. Duplicate React instances in the bundle
The project has two copies of React (e.g., one in the app and one in a linked library), causing hooks to reference the wrong instance.
// package.json of linked library
{
"dependencies": {
"react": "^18.2.0" // Should be in peerDependencies
}
}
2. Hook called outside a component
useState is called in a plain function or at module level instead of inside a React function component.
import { useState } from 'react';
// Wrong: this is not a component
function getCount() {
const [count, setCount] = useState(0);
return count;
}
export default function Counter() {
return <span>{getCount()}</span>;
}
3. Mismatched React and React DOM versions
React and React DOM are on different major versions, causing internal hook state to be incompatible.
// package.json
{
"dependencies": {
"react": "^18.2.0",
"react-dom": "^17.0.2"
}
}
The Fix
Move the useState call directly into the React function component body. Hooks must be called at the top level of a React function component or a custom hook, never inside regular functions.
import { useState } from 'react';
function getCount() {
const [count, setCount] = useState(0);
return count;
}
export default function Counter() {
return <span>{getCount()}</span>;
}
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<span>{count}</span>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
</div>
);
}
Testing the Fix
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';
describe('Counter', () => {
it('renders the initial count', () => {
render(<Counter />);
expect(screen.getByText('0')).toBeInTheDocument();
});
it('increments the count on button click', () => {
render(<Counter />);
fireEvent.click(screen.getByText('Increment'));
expect(screen.getByText('1')).toBeInTheDocument();
});
it('increments multiple times', () => {
render(<Counter />);
const button = screen.getByText('Increment');
fireEvent.click(button);
fireEvent.click(button);
fireEvent.click(button);
expect(screen.getByText('3')).toBeInTheDocument();
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/usestate-hook-placement,git add src/components/Counter.tsx src/components/__tests__/Counter.test.tsx,git commit -m "fix: move useState into component body to follow Rules of Hooks",git push origin fix/usestate-hook-placement
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run build
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
import { initBugStack } from 'bugstack-sdk'
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run npm ls react to confirm only one copy of React is installed.
- Run the test suite to confirm hooks work correctly.
- Open a pull request with the hook placement fix.
- Have a teammate review and approve the PR.
- Merge to main and verify the component renders in staging.
Frequently Asked Questions
BugStack checks for duplicate React instances, validates hook placement against the Rules of Hooks, and runs the component through render tests to confirm it works.
All fixes go through your CI pipeline and team review as pull requests. Nothing reaches production without your approval.
Run npm ls react to see all installed copies. If you see more than one, add React to peerDependencies in any linked libraries and delete node_modules to reinstall.
Yes, custom hooks (functions starting with 'use') can call useState. The rule is that hooks must be called from React components or other custom hooks, not from plain functions.