use-event-callback
use-event-callback copied to clipboard
remove potential race condition updating the ref
Turns out you can assign to react refs during a render cycle, so this PR does that instead of using a layout effect to update the ref. This removes the chance that something happens between the useEvent hook being called and the useLayoutEffect occurring.
// not sure this I like assigning to a ref during the method call, but React recommends it for certain circumstances: ... ref.current = fn;
According to Caveats of useRef:
- Do not write or read ref.current during rendering, except for initialization. This makes your component’s behavior unpredictable.
doing ref.current = fn during rendering doesn't seem to be allowed. See also a comment.