React version mismatch – Hooks can only be called inside the body of a function component

Loading

This error occurs when React Hooks are used incorrectly or when there are React version mismatches. Here’s how to resolve it:

Primary Solutions

1. Verify Hook Usage

// Correct Hook usage
function MyComponent() {
  const [state, setState] = useState(null); // ✅ Inside function component
  useEffect(() => { /* ... */ });          // ✅ Inside function component
  return <div>Example</div>;
}

// Wrong usage examples:
class MyClass extends React.Component {
  render() {
    const [state] = useState(null); // ❌ Inside class component
    return <div>Example</div>;
  }
}

function myRegularFunction() {
  const [state] = useState(null); // ❌ Outside component
}

2. Check React Version Consistency

# Check installed versions
npm list react react-dom

# Fix version mismatches
npm install react@latest react-dom@latest

Common Scenarios

3. Multiple React Versions

// Add this to your app entry point to detect multiple React copies
if (process.env.NODE_ENV === 'development') {
  const whyDidYouRender = require('@welldone-software/why-did-you-render');
  whyDidYouRender(React, {
    trackAllPureComponents: true,
  });
}

4. Webpack Alias Fix

// webpack.config.js
module.exports = {
  resolve: {
    alias: {
      react: path.resolve('./node_modules/react'),
      'react-dom': path.resolve('./node_modules/react-dom')
    }
  }
};

Framework-Specific Solutions

5. Next.js Configuration

// next.config.js
module.exports = {
  webpack: (config) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      react: path.resolve('./node_modules/react'),
      'react-dom': path.resolve('./node_modules/react-dom')
    };
    return config;
  }
};

6. Create React App Fix

# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install

Advanced Debugging

7. Detect Multiple React Copies

// Add to your entry file
console.log('React version:', React.version);
console.log('React DOM version:', ReactDOM.version);

// Check where React is loaded from
console.log('React path:', require.resolve('react'));
console.log('ReactDOM path:', require.resolve('react-dom'));

8. Yarn Resolution (for monorepos)

// package.json
{
  "resolutions": {
    "react": "18.2.0",
    "react-dom": "18.2.0"
  }
}

Common Mistakes

  • Using Hooks in class components
  • Calling Hooks conditionally
  • Having multiple React versions in node_modules
  • Incorrect Webpack/Rollup configuration
  • Mixing npm and yarn in the same project

Troubleshooting Checklist

  1. [ ] Verify all Hook calls are at the top level of function components
  2. [ ] Check for consistent React versions across dependencies
  3. [ ] Look for duplicate React installations
  4. [ ] Validate bundler configuration (Webpack/Rollup)
  5. [ ] Ensure no conditional Hook calls
  6. [ ] Check custom Hooks follow rules
  7. [ ] Test with minimal reproducible example

Verification Steps

  1. Create a test component:
function TestHooks() {
  const [count] = useState(0);
  return <div>{count}</div>;
}
  1. Check for errors when rendering this component.

Leave a Reply

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