Skip to content

Effect Events

The Course
•
15 min study

This study group chat connects to a room in an effect. A new message shows as a notice, marked (muted) when the Muted box is ticked.

A chat connection React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useState } from "react"; import { connect } from "./chat.js"; export default function App() { const [room, setRoom] = useState("react"); const [muted, setMuted] = useState(false); const [notice, setNotice] = useState(""); useEffect(() => { const disconnect = connect(room, (message) => { setNotice(muted ? `(muted) ${message}` : message); }); return disconnect; }, [room, muted]); return ( <main> <h1>Study group chat</h1> <div className="toolbar"> <select aria-label="Room" value={room} onChange={(e) => setRoom(e.target.value)}> <option value="react">react</option> <option value="hooks">hooks</option> </select> <label> <input type="checkbox" checked={muted} onChange={(e) => setMuted(e.target.checked)} /> Muted </label> </div> <p>{notice || "Waiting for messages…"}</p> </main> ); } // A pretend connection to a study-group chat room. A real one would use a // WebSocket; this one sends a message every second. export function connect(room, onMessage) { console.log(`connected to ${room}`); let n = 0; const id = setInterval(() => onMessage(`Message ${++n} in ${room}`), 1000); return () => { console.log(`disconnected from ${room}`); clearInterval(id); }; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Predict

Wait for Message 3, then tick Muted. What does the console show, and what's the next message?

Check your prediction

The console shows disconnected from react and connected to react, and the next notice is (muted) Message 1 in react: the count restarted. Ticking a checkbox reconnected to the chat.

Why it reconnects

The effect reads muted, so muted is in its dependency list. When muted changes, React cleans up the effect, disconnecting, and runs it again, reconnecting. Leaving muted out of the list would be worse: the effect would keep the first render's muted forever, and the checkbox would stop working:

JavaScript
useEffect(() => {
  const disconnect = connect(room, (message) => {
    setNotice(muted ? `(muted) ${message}` : message);
  });
  return disconnect;
}, [room, muted]);

But muting has nothing to do with which room to connect to. Only room should cause a reconnect. muted is only needed later, when a message arrives.

useEffectEvent

useEffectEvent wraps that "when a message arrives" logic into a function that always sees the latest props and state, and that isn't a dependency:

JavaScript
import { useEffect, useEffectEvent, useState } from "react";
JavaScript
const onMessage = useEffectEvent((message) => {
  setNotice(muted ? `(muted) ${message}` : message);
});

useEffect(() => {
  const disconnect = connect(room, (message) => onMessage(message));
  return disconnect;
}, [room]);

Make the change and repeat the experiment. Ticking Muted marks the next message (muted), but the console shows no reconnect and the count carries on. Changing Room still reconnects, as it should.

Rules

  • Call the function an effect event returns only from inside effects, including callbacks an effect sets up, like this message handler. Don't call it during render or pass it to other components.
  • Use it for the parts of an effect that react to an event, not for hiding real dependencies. If changing a value should restart the effect, it stays in the list.

useEffectEvent became stable in React 19.2. In older code you'll see the same job done with a ref holding the latest value.

Exercise

Count while muted

While muted, show how many messages arrived since muting, as (muted) 3 new messages, without reconnecting. Unticking Muted resets the count.

Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useState } from "react"; import { connect } from "./chat.js"; export default function App() { const [room, setRoom] = useState("react"); const [muted, setMuted] = useState(false); const [notice, setNotice] = useState(""); useEffect(() => { const disconnect = connect(room, (message) => { setNotice(muted ? `(muted) ${message}` : message); }); return disconnect; }, [room, muted]); return ( <main> <h1>Study group chat</h1> <div className="toolbar"> <select aria-label="Room" value={room} onChange={(e) => setRoom(e.target.value)}> <option value="react">react</option> <option value="hooks">hooks</option> </select> <label> <input type="checkbox" checked={muted} onChange={(e) => setMuted(e.target.checked)} /> Muted </label> </div> <p>{notice || "Waiting for messages…"}</p> </main> ); } // A pretend connection to a study-group chat room. A real one would use a // WebSocket; this one sends a message every second. export function connect(room, onMessage) { console.log(`connected to ${room}`); let n = 0; const id = setInterval(() => onMessage(`Message ${++n} in ${room}`), 1000); return () => { console.log(`disconnected from ${room}`); clearInterval(id); }; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

A mutedCount state. The effect event increments it with an updater when muted is true.

Hint 2: a first step

Reset it in the checkbox's onChange, an event handler, not in an effect.

Show one solution
JavaScript
const [mutedCount, setMutedCount] = useState(0);

const onMessage = useEffectEvent((message) => {
  if (muted) setMutedCount((n) => n + 1);
  else setNotice(message);
});
JSX
<input type="checkbox" checked={muted} onChange={(e) => {
  setMuted(e.target.checked);
  setMutedCount(0);
}} />
JSX
<p>{muted ? `(muted) ${mutedCount} new messages` : notice || "Waiting for messages…"}</p>

Was this article helpful?

Your response is saved on this device.