Error: Rendered more hooks than during the previous render. #3201
-
|
I am using Next.js. In my code, if I place session check BEFORE any react hook, I will get an error: The way I get around it is by moving the The issue with this is that, the unauthenticated user can view the data by inspecting the rest calls, and we make unnecessary rest calls to the server. How do we do early termination? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
useEffect(() => {
// still loading, early return
if (!session) {
return null
}
// load some data
loadAllTheThingsPostHaste()
}, [session]) |
Beta Was this translation helpful? Give feedback.
-
|
That error, "Rendered more hooks than during the previous render", it's an error message that originates from React. It means that the number of How to fix itThe Problem This usually happens when you use a React hook inside of a conditional statement (like an if statement), a loop, or a nested function. React requires that hooks be called in the exact same order on every render. When a conditional statement prevents a hook from running on a subsequent render, the order gets thrown off, causing this error. The Solution To fix this, you must ensure that all React hooks are called at the top level of your functional component, before any return statements or conditional logic. Here's an example of bad code that will trigger the error: And here is the correct way to structure the code: |
Beta Was this translation helpful? Give feedback.
@crzyjcky