About useEffectEvent
useEffectEvent is a React hook for situations where you want to read the latest props or state from inside an Effect, but you don't want the Effect to re-run when those values change.
The problem it solves
For example, suppose you want to connect to a chat room and show a notification using the current theme when the connection is established.
function ChatRoom ({ roomId , theme }) { useEffect (() => { const connection = createConnection ( roomId ); connection . on ( ' connected ' , () => { showNotification ( ' Connected ' , theme ); }); connection . connect (); return () => connection . disconnect (); }, [ roomId , theme ]); // Including theme causes a reconnect every time the theme changes }
Enter fullscreen mode
Exit fullscreen mode
If you leave theme out of the dependency array, you get a lint error; if you include it, simply switching the theme triggers a reconnection.…