Home > Software design >  Issue declaring a function component in React
Issue declaring a function component in React

Time:11-09

I'm attempting to declare a function component in React, so that I could use my custom hook for making API calls. I'm getting a rules-of-hooks that my hook useGet cannot be called inside a callback. In my eyes I am declaring a function component, I must be missing something?

Example:

export const MyComponent = () => {
  const [data, setData] = useState();

  useEffect(() => {
    const { getData } = useGet("myUrl");
    setData(getData);
  }, [getData]);


  return (
     <div>{data}</div>
  );
};

CodePudding user response:

It's true that hooks can only be called in functional components, but hooks also need to be called at the top level of a component. You're trying to call useGet inside the useEffect, which is not allowed. If I'm not mistaken you can probably just move the line const {getData} = useGet("myUrl"); 2 rows up and it should work.

CodePudding user response:

It seems that you actually invoke your custom hook from inside a callback which is inside useEffect. We should call react hooks on the top level of a component function.

Maybe it is better not to use a hook but just create and import fetching function or call fetch api right from inside useEffect like that https://designcode.io/react-hooks-handbook-fetch-data-from-an-api

CodePudding user response:

You are correct in having created a functional component.

Let's go back to the official React documentation and look at the Rules of Hooks

Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns.

Calling hooks at any location that is not the top level will cause unexpected behavior.

  • Related