How to avoid error : Invalid hook call. Hooks can only be called inside of the body of a function component? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to avoid error : Invalid hook call. Hooks can only be called inside of the body of a function component? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Is there any way please to allow using react hooks in my function ? because I won’t pass dispatch variable in parametres of this function in all my calls

No, there’s no way that you can use a hook in your function. You can only use hooks in (functional) React components. Information here.

What you can do in your case, is create a custom hook (say useAxiosQuery) which retrieves the dispatch function and automatically injects it, such as:

const useAxiosQuery = (endpoint) => {
  const dispatch = useDispatch();
  
  return getAxiosQuery(endpoint, dispatch);
}
We are here to answer your question about How to avoid error : Invalid hook call. Hooks can only be called inside of the body of a function component? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji