useEffectOnceLoading saved progress…

useEffectOnce

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.

Signature

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.

Examples

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)

Notes

  • Runs after mount, not during render. Like every effect, it fires after React commits the first render to the screen — never synchronously while the component is rendering.
  • Re-renders do not re-run it. Once it has run, later renders leave it alone, whatever the props or state do.
  • Cleanup is optional. If effect returns a function, run it on unmount. If it returns nothing, unmount must not error.
  • You may assume a single mount. Under React 19 outside StrictMode, effects are not double-invoked, so the effect runs exactly once per mount.
Loading editor…