Alfred
Alfred

Reputation: 447

Why I am getting error invalid hook call when I am calling it inside a function

I have a function that is called over multiple components and I wanted to put it in a helpers file like this:

import { useDispatch } from "react-redux";
import { quoteActions } from "../../_actions";
export const nextScreen = () => {
  const dispatch = useDispatch();
  dispatch(quoteActions.nextStep());
  dispatch(quoteActions.disableContinue(true));
};

Then when I go within a component where I have to use that function:

import {nextScreen} from '../helpers/';
function Screen1(props){
 useEffect(()=>{
   props.ref.current.addEventListener("click",nextScreen);
   return ()=> props.ref.current.removeEventListener("click",nextScreen);
},[])
 return(
  ...
)
}

if I declare nextScreen inside Screen1 component it works but not if I put it in a separate file, why? I tried importing React in the file I declared nextScreen but it didn't fix it, also tried returning null

Upvotes: 0

Views: 48

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53994

Functions that use hooks (like useDispatch) are called custom hooks, you need to add the use prefix to help the linter check for Rules Of Hooks violations.

export const useNextScreen = () => { ... };

Aside from the error, this code won't work as you must call hooks on the top level, the logic should be:

import { nextScreen } from "../helpers/";
function Screen1(props) {
  const dispatch = useDispatch();

  useEffect(() => {
    const nextScreen = () => {
      dispatch(quoteActions.nextStep());
      dispatch(quoteActions.disableContinue(true));
    };
    props.ref.current.addEventListener("click", nextScreen);
    return () => props.ref.current.removeEventListener("click", nextScreen);
  }, [dispatch]);
  return <></>;
}

Upvotes: 1

Related Questions