Please help me resolve this problem. I am working on a Project in Next.js and have been facing this error and nothing is helping me resolve it.
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:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
⨯ TypeError: Cannot read properties of null (reading 'useContext')
at ReadyProjectClientPage (./src/components/admin-side/ready-project/ReadyProjectClientPage.js:31:76)
digest: "3449185741"
Here is the ReadyProjectClientPage.js file mentioned in the error:
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { AlertContext } from "@/context/AlertContext";
import { useContext } from "react";
// Other imports
const ReadyProjectClientPage = (props) => {
const { showAlert } = useContext(AlertContext);
const addReadyProjectS1Handler = async e => {
e.preventDefault();
// addReadyProjectS1Service is a function which runs on the client, checks the input before passing it to the Firebase server action function to add the data to database. No hook is called in this function, however, `showAlert()` returned by the `useContext(AlertContext)` is passed to this function to be called in case of invalid input.
const data = await addReadyProjectS1Service(
readyProjectS1,
showAlert,
setShowSpinner,
);
}
// showAlert passed to other similar functions as well
// Other code
return (
<>
{/* JSX */}
</>
)
}
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 AlertContext.js file:
"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 layout.js file in which I have put the AlertProvider:
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 visited the this link to React official site provided in the error description. Under the Duplicate React section, it says:
If you use Node for package management, you can run this check in your project folder:
npm ls reactIf you see more than one React, you’ll need to figure out why this happens and fix your dependency tree.
I ran the command on my terminal and here is the result:
PS C:\Users\user\Desktop\project> npm ls react
[email protected] C:\Users\user\Desktop\project
+-- @reduxjs/[email protected]
| `-- [email protected] deduped
+-- [email protected]
| +-- [email protected] deduped
| `-- [email protected]
| `-- [email protected] deduped
+-- [email protected]
| `-- [email protected] deduped
+-- [email protected]
| `-- [email protected] deduped
+-- [email protected]
| +-- [email protected] deduped
| `-- [email protected]
| `-- [email protected] deduped
+-- [email protected]
| `-- [email protected] deduped
`-- [email protected]
Then it says:
You can also try to debug this problem by adding some logs and restarting your development server:
// 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 noticed that in any Next.js project, window.React1 pasted in node_modules/react-dom/index.js is not accessible in any component and returns undefined, so console.log(window.React1 === window.React2); always returns false. However in the React project, window.React1 pasted in node_modules/react-dom/index.js is accessible in React components and returns an object.
I have also added react and react-router-dom to peer-dependencies as mentioned in another answer.
{
"name": "mehraz",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@reduxjs/toolkit": "^2.2.3",
"firebase": "^10.11.0",
"next": "14.2.1",
"react-icons": "^5.1.0",
"react-redux": "^9.1.1",
"react-slick": "^0.30.2",
"slick-carousel": "^1.8.1",
"ulid": "^2.3.0"
},
"peerDependencies": {
"react": "^18",
"react-dom": "^18"
},
"devDependencies": {
"autoprefixer": "^10.4.19",
"eslint": "^8",
"eslint-config-next": "14.2.1",
"postcss": "^8.4.38",
"tailwindcss": "^3.4.3"
}
}
addReadyProjectS1Service? Because you're not calling that as a hook. If it calls any hooks, that's a violation of the rules of hooks. Why are you importinguseRouter? You don't show it being called, are you calling it illegally? etc. etc.