Created
September 19, 2019 03:08
-
-
Save ricokahler/c207aaadc42de3a133490b24c4dddd64 to your computer and use it in GitHub Desktop.
Only add the event listener once
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useCallback } from 'react'; | |
function usePullValue(value) { | |
const ref = useRef(value); | |
useLayoutEffect(() => { | |
ref.current = value; | |
}, [value]); | |
return useCallback(() => { | |
return ref.current; | |
}, []) | |
} | |
function MyComponent() { | |
const ref = useRef(); | |
const [someUpdatingValue, setSomeUpdatingValue] = useState(0); | |
const getSomeUpdatingValue = usePullValue(someUpdatingValue); | |
useEffect(() => { | |
const el = ref.current; | |
const handler = () => { | |
const someUpdatingValue = getSomeUpdatingValue(); | |
// do something with _latest_ `someUpdatingValue` | |
}; | |
el.addEventListener('click', handler); | |
return () => { | |
el.removeEventListener('click', handler); | |
}; | |
}, [getSomeUpdatingValue]); | |
return <div ref={ref}>{/* blah */}</div>; | |
} | |
export default MyComponent; |
There's also a simpler use case for usePullValue
which is just removing reactivity of a dependency of an effect.
function Counters() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
const getB = usePullValue(b);
// this effect only fires when `a` changes and `react-hooks/exhaustive-deps` doesn't yell at me
useEffect(() => {
const latestB = getB();
setA(a + latestB);
}, [a, getB]);
return // ...
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The example above demonstrates
usePullValue
.usePullValue
is a hook that will wrap values with a ref and sync that ref with the latest state usinguseLayoutEffect
. It returns a memo'd callback that is used to pull that current value out of the ref.The example usage attaches an event listener to a DOM element. In the handler,
getSomeUpdatingValue
in invoked to pull the latest value from the ref.This is different from the react team's recommend approach of getting update-to-date values in callback. Their recommended approach is to remove the handler function and replace it with a new handler function that closes over the latest desire value.
There's nothing wrong with that approach but, as an alternative, you can write something that will pull the latest value at the time the handler is run.
it's kind like an eager vs lazy thing?
pick ur poison