Home > Software design >  How to fix Error: Rendered more hooks than during the previous render when using SWR with useEffect
How to fix Error: Rendered more hooks than during the previous render when using SWR with useEffect

Time:01-09

I a having an issues using SWR with useEffect hook.

I am getting the error Rendered more hooks than during the previous render.

My code is as follows:

const { id } = router.query;
  const { data: recipe } = useRecipe(id);

  if (recipe) {
    useEffect(() => {
      if (typeof post.title === "string") {
        setTitle(recipe.title);
      }
    }, [recipe]);
  }

  if (!recipe) {
    return <div>Loading...</div>;
  }

useRecipe is a custom SWR hook that works perfect, as when I comment the useEffect out the data loads as expected. If I move the useEffect above the conditional recipe check i get recipe is undefined as you would expect.

I'd love to understand why I am getting the error 'Rendered more hooks than during the previous render'.

CodePudding user response:

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. you can read more in the documentation here

In your case, you can do:

const { id } = router.query;
const { data: post } = usePost(id);

useEffect(() => {
  if (recipe && typeof post.title === "string") {
    setTitle(post.title);
  }
}, [recipe]);

if (!recipe) {
  return <div>Loading...</div>;
}

return ....;
  •  Tags:  
  • Related