0

I have some custom hook.

For example

function useToggle(initialValue: boolean): [boolean, VoidFn] {
    const [val, setVal] = useState<boolean>(initialValue);
    const toggle = setVal(prevVal => !prevVal);
    return [val, toggle];
}

It's simple and clean and works fine.

But, if I use this values in other hooks, I get some warnings, because the eslint can't understand this function is already memorized.

const [myBoolVal, toggleMyVal] = useToggle(false);
const handleClick = useCallback(() => toggleMyVal(), []); // <-- I got a warning here. My IDE talks me I have to put "toggleMyVal" into dependency array.

return <button onClick={handleClick}>{myBoolVal}</div>;

How to prevent this? Maybe there is some way to mark return value as memorized

Dmitry
  • 551
  • 6
  • 19
  • checkout this answer: [enter link description here](https://stackoverflow.com/questions/64642943/use-custom-hook-inside-a-callback-in-react-js) – Mohammad Hussein Rostami Jun 01 '23 at 11:12
  • Did you get an eslint warning? – Lin Du Jun 01 '23 at 12:58
  • @LinDu yes, I forgot "eslint" tag – Dmitry Jun 01 '23 at 16:18
  • Eslint is always angry when you use outside variables/functions inside `useCallback` `useEffect` etc without including them in the dependency array. Solution - either include it (that could cause issues) or write a comment above the dependency array to disable that specific Eslint rule for that 1 line as it is not required to be in the dependency array. The better question is - why are you using a callback hook for something that is simple and a function that only gets executed when a user clicks a button? No complex or expensive logic there... would just remove it – Lith Jun 01 '23 at 16:43
  • @Lith It's only simple example. Of course I'm using more complex logic in my hooks – Dmitry Jun 01 '23 at 17:28

0 Answers0