React Foundations · Effects & Refs

Separating events from effects

useEffectEvent

Separating events from effects

An effect often needs a value from the latest render, but should not restart when that value changes. A chat room reconnects when roomId changes, yet the notification it shows should read the current theme:

useEffect(() => {
  const connection = connect(roomId);
  showNotification(theme); // reads theme, but should not depend on it
  return () => connection.disconnect();
}, [roomId]);

Add theme to the array and the room reconnects on every theme change — wrong. Leave it out and the effect closes over a stale theme from the render that created it.

useEffectEvent pulls that read into an Effect Event: a function that always sees the latest values without being a dependency.

const onConnect = useEffectEvent(() => {
  showNotification(theme);
});

useEffect(() => {
  const connection = connect(roomId);
  onConnect();
  return () => connection.disconnect();
}, [roomId]);

The effect still depends only on roomId, so it reconnects only when the room changes. When it runs, onConnect reads the current theme. Call Effect Events from inside effects, never during render.

Your job in App.jsx is to read the latest theme on reconnect without reconnecting when the theme changes.

Challenge

A chat connection reconnects every time the theme changes, when it should only reconnect when the room changes. Export an App component from App.jsx that keeps a roomId and a theme in state and appends the theme to a log each time it connects. The connection effect depends only on roomId and reads the latest theme through an Effect Event.

Render the log in a <p data-testid="log">, a Toggle theme button, and a Change room button. The Test clicks the Toggle theme button, then changes the room, and expects your log to read light,dark. The starter lists theme as a dependency, so it reconnects on the theme change and the Test fails.

App.jsx
import { useEffect, useState } from 'react';

export function App() {
  const [roomId, setRoomId] = useState('general');
  const [theme, setTheme] = useState('light');
  const [log, setLog] = useState([]);

  useEffect(() => {
    setLog((entries) => [...entries, theme]);
  }, [roomId, theme]);

  return (
    <div>
      <p data-testid="log">{log.join(',')}</p>
      <button onClick={() => setTheme((current) => (current === 'light' ? 'dark' : 'light'))}>
        Toggle theme
      </button>
      <button onClick={() => setRoomId('random')}>Change room</button>
    </div>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.