React introduces useEffectEvent which was previously called useEvent in experimental mode. Though it states that it adds ton of advantages. I can’t find any sufficient examples to support this. In the React documentation site the challenges they mentioned at the end of the page can easily be solved except one.
The first challenge of fixing static timer(Challenge 2 of 4) solves well with useEffectEvent, since we do not have to add increment as dependency since it takes it in runtime. The functions declared inside this hook doesn’t take snapshot of the states and props during first render and attaches it entirely with an event. If that is the case, there is no need to add even a state updater inside the function. Also how does React does this? I know that when an event listener is added to an event the fixed reference value of the function in that render is attached with the event. Since using this hook makes React using the latest state and props. How and where does React stores it?
Also in Challenge 4 of 4 of Fixing a Delayed Notification, the use of useEffectEvent is solely to abide by the dependency linter. This is the code in documentation:
const onConnected = useEffectEvent(connectedRoomId => {
showNotification('Welcome to ' + connectedRoomId, theme);
});
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.on('connected', () => {
setTimeout(() => {
onConnected(roomId);
}, 2000);
});
connection.connect();
return () => connection.disconnect();
}, [roomId]);
And here is the code without useEffectEvent:
3. useEffect(() => {
4. const connection = createConnection(serverUrl, roomId);
5. connection.on('connected', () => {
6. setTimeout(() => {
7. showNotification('Welcome to ' + roomId, theme);
8. }, 2000);
9. });
10. connection.connect();
11. return () => connection.disconnect();
12. }, [roomId]);
Can we say that the introduction of useEffectEvent is primarily for 2 reasons:
- To abide by the dependency linter.
- To make a way out of how React works i.e every render has its own version of event handlers so attaching it, would request the user to add a dependency and hence using this Hook, the updated version of the function is called with current state and props?
quest is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.