Sub topic 2
Extracting Non-Reactive Logic with `useEffectEvent`
Assume you know JavaScript closures, React function components, useState, and basic useEffect cleanup. This chapter uses React’s useEffectEvent API.
Extracting Non-Reactive Logic with `useEffectEvent`
An Effect synchronizes a component with an external system, such as a chat connection or timer. Its dependency array lists reactive values that should cause synchronization again.
Sometimes an Effect reads a value only while responding to an external event. That value should be current, but changing it should not restart the synchronization.
import { useEffect, useEffectEvent } from 'react';
import { createConnection } from './chat.js';
import { showNotification } from './notifications.js';
function ChatRoom({ roomId, theme }) {
const onConnected = useEffectEvent(() => {
showNotification('Connected!', theme);
});
useEffect(() => {
const connection = createConnection(roomId);
connection.on('connected', onConnected);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
}Here, roomId controls which chat room the Effect synchronizes with. theme controls how the notification looks, but changing the theme does not require a new chat connection. The Effect Event separates that non-reactive notification logic from the reactive connection logic.
Reading the Latest Props and State
When React calls an Effect Event, its callback reads the latest props and state. This avoids stale values in subscriptions, timers, and other callbacks that run later.
const onTick = useEffectEvent(() => {
setCount((current) => current + increment);
});
useEffect(() => {
const id = setInterval(onTick, 1000);
return () => clearInterval(id);
}, []);The interval is created once. Each tick uses the current increment, even after increment changes.
Passing Reactive Values as Arguments
If a value identifies what the Effect must synchronize with, keep it in the dependency array. Pass it explicitly to the Effect Event when the event occurs.
const onVisit = useEffectEvent((visitedUrl) => {
logVisit(visitedUrl, shoppingCart.length);
});
useEffect(() => {
onVisit(url);
}, [url]);A new url records a new visit. The current cart length is read when the visit is recorded, but cart changes do not create extra visits.
Rules of Effect Events
- Call an Effect Event only from an Effect in the same component.
- Do not call it during rendering.
- Do not pass it to another component or custom Hook.
- Do not list it in the Effect dependency array.
- Keep genuinely reactive triggers in the dependency array.
- Do not use it to hide a missing dependency.
Exercise
In the chat example, should changing roomId or changing theme reconnect the chat?
Show answer
Changing roomId should reconnect the chat. Changing theme should only affect the next notification.