Build a custom hook that runs a side effect a single time, right after the component mounts, and never again — no matter how many times the component re-renders afterward. React's useEffect re-runs whenever one of its dependencies changes; with an empty dependency list it runs only on mount. useEffectOnce(effect) packages that pattern behind a name, and runs the effect's cleanup function (if it returns one) when the component unmounts.
function useEffectOnce(effect: () => (void | (() => void))): void;
The hook returns nothing. effect is the function to run once; if it returns a function, that returned function is the cleanup that runs on unmount.
function Chat({ roomId }) {
// Runs ONCE after this component first appears, even if `roomId` or other
// props change and trigger re-renders. The returned function tears down
// the connection when the component unmounts.
useEffectOnce(() => {
const conn = openConnection();
return () => conn.close();
});
return <div>Connected</div>;
}
// Across the component's life, the effect fires exactly one time:
// mount → effect runs (call count: 1)
// re-render → effect skipped (call count: 1)
// re-render → effect skipped (call count: 1)
// unmount → cleanup runs (cleanup count: 1)
effect returns a function, run it on unmount. If it returns nothing, unmount must not error.StrictMode, effects are not double-invoked, so the effect runs exactly once per mount.