So you've decided to hop on board the React Hooks train. Welcome to a fun, wild ride. They can add a great deal of declarative power to React. In my opinion, hooks were the missing puzzle piece in the API developed by React.

You get your first custom hook working, everything looks good in prod. Then, like the responsible developer you are, you write a simple test for it and run it.


"Invariant Violation: Hooks can only be called inside the body of a function component." But... you ARE!

A likely culprit is that you have multiple copies of React in your system. Rather than hunting through yarn.lock files, you can most reliably confirm this with some simple debugging logs:

// Add this in node_modules/react-dom/index.js
window.React1 = require('react');

// Add this in your component file
window.React2 = require('react');
console.log(window.React1 === window.React2);

Most people focus on forcing the same react package using Yarn resolutions. However, if you're only getting this error in your tests, the most likely culprit is a different version of react-test-renderer. You can fix it by adding these lines to your package.json file if you're using Yarn:

"resolutions": {
    "react-test-renderer": "your.reaction.version"

Hope that helps!