AceDevHub
Intermediate React Interview QuestionsIntermediateConcept

React · Question 46

What problem does useEffectEvent solve in modern React?

Direct answer

useEffectEvent lets Effect logic read the latest committed props and state without making that non-reactive logic a reason for the Effect itself to re-synchronize.

ChatRoom.jsx
function ChatRoom({ roomId, muted }) {
  const onConnected = useEffectEvent(() => {
    if (!muted) {
      showNotification("Connected");
    }
  });

  useEffect(() => {
    const connection = createConnection(roomId);
    connection.on("connected", onConnected);
    connection.connect();

    return () => connection.disconnect();
  }, [roomId]);

  return <h1>{roomId}</h1>;
}

The connection is reactive to roomId, but the notification can read the latest muted value without reconnecting merely because the preference changed.