useGlobalEvent does not update when handler function changes
sjdemartini opened this issue · comments
Describe the bug
As of this change in May 58907dc#diff-0a8432ca913ab2abf25a4371c9b5336ce6d6aad4c102d01aa3c862d747dd79c7L16-L17, useGlobalEvent
broke, since changes to the handler function do not update the local ref (and so stale versions of the handler will be called). It seems likely that this will have affected other hooks as well.
To Reproduce
Steps to reproduce the behavior:
- Use
useGlobalEvent
with a callback that changes, e.g.:const [num, setNum] = useState(0); useGlobalEvent("keydown", undefined, () => { console.log("keydown num is ", num); setNum((prevNum) => prevNum + 1); }); console.log("actual num is ", num);
- Press any key
- Notice in the console that
actual num is ...
keeps incrementing, while the former log statement will always readkeydown num is 0
, despite the fact that the handler foruseGlobalEvent
is an arrow-function that is redefined on every render. (The first version of the callback is stored and souseGlobalEvent
is stale)
Example from the above demo:
21:14:21.821 Main.tsx:31 actual num is 0
21:14:21.923 Main.tsx:31 actual num is 0
21:14:25.936 Main.tsx:28 keydown num is 0
21:14:25.936 Main.tsx:31 actual num is 1
21:14:26.670 Main.tsx:28 keydown num is 0
21:14:26.671 Main.tsx:31 actual num is 2
21:14:27.887 Main.tsx:28 keydown num is 0
21:14:27.888 Main.tsx:31 actual num is 3
Additional context
It seems this line should have handlerValue
as the useCallback
dependency, rather than handlerRef
, which will never cause the callback to update: 58907dc#diff-0a8432ca913ab2abf25a4371c9b5336ce6d6aad4c102d01aa3c862d747dd79c7R22
Hi @sjdemartini thanks for the update, I'll dig into it asap
Hi @sjdemartini
Please check PR #294 and let me know if it works for you.
On my side works perfectly fine...