Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react hooks: how to handle co-dependent useCallbacks

the react hook's linter likes to be strict with the DependencyList. That leads to the following broken situation where 2 event handlers depend on each other. Since the functions are registered with addEventListener I know if they ever change it'll introduce a memory leak so the easy thing to do is just empty the dependency list-- but what is the right way to handle this while playing by the linter's rules?

const onMouseMove = useCallback((e) => {
  if (!isSwipe(e)) {
    onMouseUp(e)
  }
}, [onMouseUp])

const onMouseUp = useCallback((e) => {
  document.removeEventListener('mousemove', onMouseMove)
}, [onMouseMove])
like image 572
Matt K Avatar asked Jul 24 '19 15:07

Matt K


1 Answers

useCallback is essentially a version of useMemo, specialized for memoizing functions. If two functions are co-dependent and can't be memoized separately with useCallback, they can be memoized together with useMemo:

const { onMouseMove, onMouseUp } = useMemo(() => {
    const onMouseMove = (e) => {
        if (!isSwipe(e)) {
            onMouseUp(e)
        }
    };
    const onMouseUp = (e) => {
        document.removeEventListener('mousemove', onMouseMove)
    }
    return { onMouseMove, onMouseUp };
}, [/* shared deps*/]);

This is the general pattern I'd use to memoize functions together, and I think it's the simplest answer to the general question. But I'm not sure, looking at the actual code here, that it's the best approach - the removeEventListener may not work if the onMouseMove is a different function than the one that was registered due to useMemo recalculating. Might be more of a useEffect sort of use-case, in practice.

like image 145
Retsam Avatar answered Sep 23 '22 07:09

Retsam