Sku
Sku

Reputation: 173

invalid hook call with nextjs inside custom hook

I'm getting a invalid hook call error when using state inside my custom hook. Here's my code

import { useState } from 'react';

export default function useFetch() {
  const [randomValue, setRandomValue] = useState<number>();
  setRandomValue(3);

  return randomValue;
}

the hook is inside my hooks folder on the path: ./src/hooks

any reason for that?

Upvotes: 0

Views: 1299

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187044

Your comment mentions you call useFetch() from inside useEffect(). That's where your problem is.

Hooks are only valid when called during render of a component. useEffect() is triggered after a render. So you cannot call any hook from inside useEffect.

It's hard to advise how to fix that since you haven't posted that code.


Also, and this is equally important, never call a state setter function during render. And remember that hook functions run when the component renders. Setting state triggers a render, so this typically results in an infinite loop.

Most of time when fetching a value and setting it in state, you should have a valid initial value for its type (like null), and a useEffect() to set something you want.

Remember that useEffect means "use side effect" where a side effect is something that a render may trigger, but is not executed synchronously every single render.

export default function useFetch() {
  const [randomValue, setRandomValue] = useState<number | null>(null);

  useEffect(() => {
    setRandomValue(Math.floor(Math.random() * 10));
  }, [setRandomValue]}


  return randomValue;
}

Upvotes: 1

Related Questions