New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Hooks + multiple instances of React #13991
Comments
So just for clarification: You were importing a hook (say I agree that this is confusing. I'm not sure though if we have a way of knowing if any other React module is rendering. AFAIK we try to run React in isolation as much as possible so that multiple React instances can work in the same global context without issues. Otherwise we could probably update the error message and mention this case as well if it's not too confusing. |
Yes, I compared This issue is to raise awareness of this case and maybe improve the error message in some way to help people that face this. It's probably very edge though. |
Yup, i tried to npm link a package i'm creating. It throws that same error since the other package is also using hooks but with its own React. I had to publish my package to NPM and then import it directly from NPM. That way the error was gone, but i hope this is fixed since publishing a package without testing it is bad, obviously |
Lerna monorepos suffer from this as well when a custom hook is defined in one package and used by another as the symlinked dependencies use their own copy of react. I have a (hacky) workaround at the moment using "prestart": "npm-link-shared ./node_modules/<other package>/node_modules . react" |
I had the same issue and I resolved it by adding:
to It's was obviously my mistake of using two copies of React but I agree that it would be great if the error message was better. I think this is maybe similar to: #2402 |
@mpeyper It works. Thanks |
@apieceofbart That worked for me. Thanks for the suggestion. 👍 |
As I understand this problem arises when there are multiple copies of React in the same bundle. Is this also a problem if two separate bundles with their own copies of React are bootstrapping their own React applications on separate dom elements, like described here: https://medium.jonasbandi.net/hosting-multiple-react-applications-on-the-same-document-c887df1a1fcd I think the latter is a common "integration" pattern used for instance in the single-spa meta-framework (https://github.com/CanopyTax/single-spa). |
I'm also having this issue even with the exact same react versions, developing hooks to be published on their own is broken when using |
Same issue here when I |
I fixed my issue by removing the caret in |
I'm using Yarn, and fixed this by forcing resolution in my
|
Same here!! |
Just wanted to leave a note here for anyone who might have had this problem in the same manner I did. We're running React and Rails with the This appears to have solved it for us. |
I'm very excited to finally put Hooks into production, and we all owe a huge thank you to everyone who made it possible. They're a ton of fun to work with and have made my code shorter and more declarative. Just as a heads up, this issue is still relevant in the released version with the same unhelpful error message of "Hooks can only be called inside the body of a function component." Is this something that can be fixed? I imagine it might become more and more prevalent as more devs start to implement the new features, and a clearer error message would go a long way in lieu of an outright "fix". Thanks again for all the hard work and congrats on the release! It's really an amazing set of features. Edit: Should have looked closer at the open PRs, just found #14690 that addresses this. Thanks @threepointone! |
@taylorham The link in the commit doesn't point to anything yet. I'll wait for it, but this is an issue I have been having since using hooks in a linked (as of |
I faced this issue in Gatsby 5 and the problem was because I violated the rule of hooks. I did not call it inside a React functional component which caused the error. |
If you're facing this issue and you're:
And you seems to only have this issue when going to the app at example.com, but the app is okay when going to localhost:5173, then do the following on example.com,
This fixed the issue for me cause the browser is caching stuff on example.com, but not on localhost:5173. |
I have this same issue |
I have this issue too and already spend almost whole day to solve it. ps: I have to complain that i have no idea why it appear. My project work in React 16.14.x. sad. |
THANK GOD! I solve my problem in the last minutes of today.
|
Hi, |
I'd take a look at it. @mchepuri I wasn't able to recreate the bug but what I noticed was that you were mixing up Default exports are in the format: //export
const Component = () => {}
export default Component
//import
import Component from '@dir' Named export are in the format: //export
const Component = () => {}
export { Component }
//import
import { Component } from '@dir'
|
I got this error by calling root.render(MyComponent()); instead of root.render(<MyComponent />) The component being rendered is using import React, {useState} from "react";
export default function MyComponent() {
const [myVar, setMyVar] = useState('testing...');
// ...
} It's a silly mistake I made, and the resulting error message is very confusing, which made me lose hours trying to fix this. |
Try this: Delete node_modules folder from any parent folders from your project
…________________________________
From: Douglas Silva ***@***.***>
Sent: Saturday, August 19, 2023 10:37:50 AM
To: facebook/react ***@***.***>
Cc: Darren Rush ***@***.***>; Manual ***@***.***>
Subject: Re: [facebook/react] Hooks + multiple instances of React (#13991)
I got this error by calling
root.render(MyComponent());
instead of
root.render(<MyComponent />)
The component being rendered is using useState, and it is defined in MyComponent.tsx, which is a TypeScript JSX module in a bundler context (webpack). TypeScript jsx option is set to react, so import React from "react" is necessary.
import React, {useState} from "react";
export default function MyComponent() {
const [myVar, setMyVar] = useState('testing...');
// ...
}
—
Reply to this email directly, view it on GitHub<#13991 (comment)>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/AAA23IJJFBSTYTBGCQOGDULXWD2W5ANCNFSM4F7UTLDA>.
You are receiving this because you are subscribed to this thread.Message ID: ***@***.***>
|
This keeps being flared as an incorrect usage of the 'useState' hook, although it doesn't seem to fall into any of the usual pitfalls to my eyes. I've tried some different strategies for removing duplicate Reacts and there's no mismatch in version. The closest I can think is that the function it's used in is later used as a constant, but I've tried ways of removing the constant with the same results. Again, this might just be a goof.
|
Hello, I also have this issue. I read through the page carefully and checked everything and could not see anything amiss. I have a custom component library in React 18.2.0 and a Project in React 18.2.0. Both use Vite for bundling. I am using serve side rendering with The issue is always occurring if I enable SSR, I don't see it if I only use client side rendering, which makes think that it might be due to that In my library I have created a dummy hook: function testHook() {
console.log('testHook: testHook');
console.log('testHook: React', React);
console.log('testHook: ReactDOM', ReactDOM);
console.log('testHook: testHook');
const [testBool, setTestBool] = useState(false);
useEffect(() => {}, []);
} I am calling this hook in my top level page component: function Page() {
//@ts-ignore
ReactDOM.testNew = 'testNew'; // I can see that this appended in my lib
//@ts-ignore
React.test = 'test'; // I can see that this appended in my lib
const test = testHook();
return <></>;
} I also checked if ./node_modules/react-dom/index.js
if (typeof window !== 'undefined') {
window.React1 = require('react');
}
./page/dummy.tsx
import React from 'react';
import ReactDOM from 'react-dom';
...
if (typeof window === 'undefined') {
return <></>;
}
@ts-ignore
window.React2 = require('react');
@ts-ignore
console.log(window.React1 === React); // true So It seems to me that I am doing everything correctly and still see this issue. I saw that the issue goes away if I do either:
Appendix:I am unsure if this helps but here are also my Vite bundling configs of my lib: /// <reference types="vitest" />
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import dts from 'vite-plugin-dts';
// https://vitejs.dev/config/
export default defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, 'src/index.ts'),
formats: ['es', 'cjs'],
name: '@workdigtital/component-library-react',
fileName: (format) => `index.${format}.js`
},
rollupOptions: {
external: ['react', 'react-dom'],
output: {
globals: {
react: 'React',
'react-dom': 'ReactDOM'
},
exports: 'named'
}
}
},
plugins: [react(), dts({ insertTypesEntry: true })],
test: {
globals: true,
environment: 'jsdom',
setupFiles: ['./src/tests/setup.ts'],
exclude: ['**/node_modules/**', '**/dist/**', '**/coverage/**', '**.stories**', '.storybook/**', '**.types**'],
coverage: {
all: true,
exclude: ['**/*.stories.tsx', '.storybook/**'],
provider: 'c8',
reporter: ['cobertura', 'html']
}
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@flaticon': path.resolve(__dirname, './node_modules/@flaticon')
}
}
}); Stack Trace:
SolutionMy issue was with a third party plugin https://socket.dev/npm/package/vite-plugin-circular-dependency, removing it helped. |
None of the above solutions worked for me until I upgraded styled-components from v5 to v6. I was even getting If you're using styled-components, try upgrading. |
I am getting "Invalid Hook Call" error for below code
Any help on this would be appreciated |
I'm getting Invalid hook call. I'm using this code from email.js: `const Contact = () => {
I'd appreciate the help |
😪😔 |
I am creating a UI library so I used useState in my library component and when I use this library in my project with npm link library or npm install library I get this error `reactjscomponents.js:2 Uncaught TypeError: Cannot read properties of null (reading 'useState') ` at t.useState (reactjscomponents.js:2:1) my package.json my webpack file module.exports = { my babel file |
I am also getting So I am guessing , it might have to do something with 1. mismatching versions of React and React DOM. or 2.more than one copy of React . In general ,
I am getting any help is appreciated |
do i have duplicate react? projetofirestore@1.0.0 C:\APP\ProjetoFirestore |
This is resolved. The issue here was that I was using two
to
So the issue was never one of these which I was thinking - hooks rules , mismatching versions of React and React DOM , more than one copy of React Or using useNavigate() . They may be an issue in some scenarios but in this particular scenario the issue was using two |
I hit this error today on a component which renders a sub-component and attaches a callback ref to that sub-component. Inside the handler for that callback ref, it was calling a method which eventually called Not sure if integral to the repro, but it also relied on accidentally double-rendering our entire dev page on page load. We were accidentally loading the entire webpack bundle twice, so the first render was getting unmounted and blown away by the second render. It was quite hard to track down and didn't fit the three things listed in the troubleshooting error message. A big part of the difficulty was that the error was being reported from a hooks/function component which was being rendered as a sibling of the aforementioned host component, not a child. |
I noticed I have duplicate react in my library How can remove ?? |
Hello, I believe I have part of the solution for this error message. This error message can present itself in multiple ways depending on the exact APIs used in your component. I believe it all boils down to React detecting multiple copies of itself, even if they are the exact same version. Issue(s):Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
TypeError: Cannot read properties of null (reading 'useState') Solution:
Run your app and hopefully the React error will be resolved! ReproducingThis error can be reproduced with this minimal setup.
I hope this helps some people out there. Thank you! |
Hi there fellow Dev's, I am struggling with this issue to, mine is related to plugin development. I created two functional components for a plugin in WordPress: one called edit (used in the back-end for displaying the plugin in the block editor) and another called RecentPosts (which is supposed to be integrated into edit.js for more functionality). Here's the code for edit:
Here's the code for RecentPosts:
After running my scripts using the command
To solve this problem, I clicked on the link provided in the error which brought me to this page. After clicking on the link provided in the red box, I got to this page. Over there, I found a list and analysis of possible causes of this error, I checked for all of them but it turned out that I didn't make any of the mistakes they referred to or violated the rules for React hooks. I also prompted ChatGPT (3.5), it gave me the following response:
As it seems to me, my code basically looks the same, as you'll see, I am not completely sure what could be causing this error. It only occurs When |
Please help me resolve this problem.
Here is the
The main issue is that I am unable to reproduce the problem. The error appears randomly, once in a few hours, mostly when I reload the page. After it appears, no matter how hard may I try to reproduce it, it would not reappear. I have manually checked all the hooks and they are all directly inside React components. Here is my "use client";
import { createContext, useState } from "react";
const AlertContext = createContext({
alerts: [],
showAlert: () => {},
hideAlert: () => {},
});
const AlertProvider = ({ children }) => {
const [alerts, setAlerts] = useState([]);
const showAlert = ({ type, message }) => {
setAlerts([{ type, message, timestamp: Date.now() }]);
};
const hideAlert = () => {
setAlerts([]);
};
return (
<AlertContext.Provider value={{ alerts, showAlert, hideAlert }}>
{children}
</AlertContext.Provider>
);
};
export { AlertProvider, AlertContext }; Here is my root import { Roboto } from "next/font/google";
import "@/app/globals.css";
import { AlertProvider } from "@/context/AlertContext";
import StoreProvider from "@/store/StoreProvider";
const roboto = Roboto({
subsets: ["latin"],
weight: ["100", "300", "400", "500", "700", "900"],
});
export const metadata = {
title: "title",
description: "description",
};
export default function RootLayout({ children }) {
return (
<>
<StoreProvider>
<AlertProvider>
<html lang="en">
<body className={roboto.className}>{children}</body>
</html>
</AlertProvider>
</StoreProvider>
</>
);
} The versions of react and react-dom are both 18.
I ran the command on my terminal and here is the result: PS C:\Users\user\Desktop\project> npm ls react
project@0.1.0 C:\Users\user\Desktop\project
+-- @reduxjs/toolkit@2.2.3
| `-- react@18.2.0 deduped
+-- next@14.2.1
| +-- react@18.2.0 deduped
| `-- styled-jsx@5.1.1
| `-- react@18.2.0 deduped
+-- react-dom@18.2.0
| `-- react@18.2.0 deduped
+-- react-icons@5.1.0
| `-- react@18.2.0 deduped
+-- react-redux@9.1.1
| +-- react@18.2.0 deduped
| `-- use-sync-external-store@1.2.0
| `-- react@18.2.0 deduped
+-- react-slick@0.30.2
| `-- react@18.2.0 deduped
`-- react@18.2.0 Then it says:
// Add this in node_modules/react-dom/index.js
window.React1 = require('react');
// Add this in your component file
require('react-dom');
window.React2 = require('react');
console.log(window.React1 === window.React2); I tried it in my current Next.js project,in a new Next.js project, and in a new React.js project using vite. I have also added
|
To people coming from search: please read this page first. It contains most common possible fixes!
Do you want to request a feature or report a bug?
Enhancement
What is the current behavior?
I had multiple instances of React by mistake.
When trying to use hooks, got this error:
hooks can only be called inside the body of a function component
Which is not correct since I was using function components. Took me a while to find the real cause of the issue.
What is the expected behavior?
Show the correct error message. Maybe detect that the app has multiple instances of React and say that it may be the reason of bugs.
The text was updated successfully, but these errors were encountered: