3

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 react If 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"
  }
}
9
  • "I have also made it sure that I am not breaking rules of Hooks" I mean no offense, but we are not going to just take your word for that, you need to post the shortest code that demonstrates the problem. It is actually not that easy to wind up with multiple different versions of React on the same page. In over 7 years of writing React, I've seen it happen once, and that was very early on. It is much more likely that you are violating the rules of hooks and don't realize it. Commented Apr 19, 2024 at 20:26
  • I have now provided additional details along with code in the question. Commented Apr 19, 2024 at 21:40
  • Again, stop assuming that you know what the problem is. You could be right (as I said it happened to me once in the better part of a decade of writing React) but you're probably wrong, and you're probably violating the rules of hooks in your code. You still have not stripped this down to a minimal reproduction case. What about 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 importing useRouter? You don't show it being called, are you calling it illegally? etc. etc. Commented Apr 20, 2024 at 13:49
  • Comment out anything that isn't necessary to reproduce the problem and just show us ALL of the code that isn't commented. In fact, just comment out everything and gradually incrementally re-introduce parts of your app until it breaks. The last thing you uncommented is your problem. Commented Apr 20, 2024 at 13:53
  • 1
    The main issue is that I am unable to reproduce the problem. The error appears randomly, mostly when I reload the page. Now I have been reloading the page in different ways for 5-10 minutes but haven't seen the error yet. Commented Apr 21, 2024 at 16:13

1 Answer 1

0

I had this happen to me and it just needed a Next.js dev server restart to clear up 🤷

In my case the stack trace only had Next.js code in it and not project code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.