Synchronize a subscription with useEffect
Connect a component to something outside React
An Effect coordinates a committed component with a resource whose lifetime React does not manage, such as a browser listener, timer or third-party widget. Import useEffect and call it at the top level. Its setup can return a function that reverses the setup. All positive examples are independent App.jsx files for the Chapter 3 client project. The displayed outcomes are predictions until browser verification is possible.
import { useEffect, useState } from 'react';function Announcements() { const [message, setMessage] = useState('Waiting'); useEffect(() => { function receive(event) { setMessage(event.detail); } window.addEventListener('station-announcement', receive); return () => window.removeEventListener('station-announcement', receive); }, []); return <p role="status">{message}</p>;}export default function App() { const [visible, setVisible] = useState(true); return <main><h1>Station notices</h1> <button onClick={() => setVisible(v => !v)}>Toggle receiver</button> <button onClick={() => window.dispatchEvent(new CustomEvent('station-announcement', { detail: 'Platform 2 open' }))}>Send notice</button> {visible && <Announcements />} </main>;}After the listener is installed, Send notice displays Platform 2 open. Toggle receiver removes the component and its listener; sending while hidden does not buffer a message. Reopening begins with Waiting. The function reference used for removal is the same one used for registration. The synthetic window event is a local stand-in for an external message source; no server is involved.
Model a timer without waiting for wall-clock time
import { useEffect, useState } from 'react';function createClock() { const listeners = new Set(); return { subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, tick() { for (const listener of [...listeners]) listener(); }, size() { return listeners.size; } };}const clock = createClock();function Elapsed() { const [ticks, setTicks] = useState(0); useEffect(() => clock.subscribe(() => setTicks(n => n + 1)), []); return <p>Ticks: {ticks}</p>;}export default function App() { const [visible, setVisible] = useState(true); return <main><h1>Training clock</h1> <button onClick={() => clock.tick()}>Advance one tick</button> <button onClick={() => setVisible(v => !v)}>Toggle counter</button> {visible && <Elapsed />} </main>;}Each activation of Advance one tick should increase the displayed count by one while the counter is mounted. No actual seconds elapse in this model. The subscription returns its own unsubscribe function. The state updater uses the previous queued value rather than capturing the first ticks value. The module-level clock is a stable resource for this single teaching fixture; production applications should give resources an explicit owner. The fake clock itself can be tested independently of React.
Apply the same lifetime to a browser timer
import { useEffect, useState } from 'react';function Stopwatch() { const [ticks, setTicks] = useState(0); useEffect(() => { const timer = setInterval(() => setTicks(n => n + 1), 1000); return () => clearInterval(timer); }, []); return <p>Timer callbacks: {ticks}</p>;}export default function App() { const [running, setRunning] = useState(false); return <main><button onClick={() => setRunning(v => !v)}>{running ? 'Stop' : 'Start'}</button> {running && <Stopwatch />}</main>;}Start mounts a counter; Stop removes it and requests cancellation of its interval. Starting again creates fresh state. Timer callbacks can be delayed by browser scheduling; this is a count of callbacks, not a precision stopwatch. Never create an interval in the render body. During a development StrictMode check at the root, a setup may be followed by cleanup and another setup before normal interaction. A correct resource remains active once, not twice. Effects are client-side and do not execute during server rendering; their timing relative to browser paint is not a universal ordering guarantee.
Practice
Use the fake clock to predict three ticks, unsubscribe, and tick again. In the approved React runtime toggle the counter off and on and confirm the count restarts. Explain what would happen if the unsubscribe function were omitted.