Interview frequency: …
Short answer
useEffectEvent separates reactive logic (which must always read the latest values) from an Effect's dependency array (which should not cause unwanted Effect re-execution).
Explanation
Sometimes useEffect needs to read current variables, such as theme or callback, without rerunning each time they change. useEffectEvent (stable in React 19.2; previously experimental_useEffectEvent) lets functions read the latest props and state without adding them to the dependency array. Do not call an Effect Event during Render or pass it to other components; use it only inside Effects.
Code example
import { useEffect, useEffectEvent } from "react";
function ChatRoom({ roomId, theme }: { roomId: string; theme: string }) {
const onConnected = useEffectEvent(() => {
showNotification("Connected!", theme); // always reads the latest theme
});
useEffect(() => {
const connection = createConnection(roomId);
connection.on("connected", () => onConnected());
connection.connect();
return () => connection.disconnect();
}, [roomId]); // reconnects only when roomId changes, not when theme changes
}Common mistakes
- Calling a function registered with useEffectEvent during Render instead of inside the Effect.