0

I am calling a function inside useEffect:

const ToggleMenu = () => {
    document.body.classList.toggle("toggle-menu-open");
    setActive(!isActive);
  };
    useEffect(() => {
        const handleEsc = (event) => {
            if (event.keyCode === 27) {
                ToggleMenu()//my function
            }
        };
    
        window.addEventListener("keydown", handleEsc);

        return () => {
            window.removeEventListener("keydown", handleEsc);
        };
    }, []);

it is working but when i run npm run build command it throws a warning like:

Warning: React Hook useEffect has a missing dependency: 'ToggleMenu'. Either include it or remove the dependency array

  • Put `ToggleMenu` into the dependency array `[]` (the second parameter to `useEffect`). – zhulien Nov 24 '21 at 07:32
  • Where is `ToggleMenu` function defined? You could wrap it in `useCallback` hook and then add it in the dependency array of the `useEffect` hook. – Yousaf Nov 24 '21 at 07:33
  • 2
    Does this answer your question? [How to fix missing dependency warning when using useEffect React Hook](https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook) – Martin Nov 24 '21 at 07:36
  • iam using this useEffect first time and i am not able understand what you said,when i call ToggleMenu into dependency array it throws a warning like this:"wrap the definition of 'ToggleMenu' in its own useCallback() Hook" – Sai Manoj v Nov 24 '21 at 07:48
  • 2
    Rewrite `ToggleMenu` as: `const ToggleMenu = useCallback(() => { document.body.classList.toggle("toggle-menu-open"); setActive(currentState => !currentState); }, []);` – Yousaf Nov 24 '21 at 08:00
  • You might want to take a look at: https://github.com/facebook/react/issues/22132 This misunderstanding is very common, which is the smell of an API that could be improved in React. – Eric Burel Nov 24 '21 at 12:55

0 Answers0