FrontendInterviews.dev

Loading problem…

325. useEffectOnce Hook

Medium•

Create a helper hook useEffectOnce that runs setup logic exactly once per mount and handles cleanup correctly.

Requirements

Implement:

function useEffectOnce(effect: () => void | (() => void)): void

Behavior

  • Execute the setup callback once when component mounts
  • Execute returned cleanup function once when component unmounts
  • Do not require consumers to pass dependency arrays

Practical Scenario

Use this hook for one-time registration logic like analytics bootstrapping, event wiring, or websocket setup.

Note

Explain how your implementation behaves under React Strict Mode development remount checks.

Constraints

  • Hook API should be minimal and type-safe.
  • Cleanup must run reliably on real unmount.
  • No external libraries.