Docs
useEventCallback

useEventCallback

Creates a callback with a stable identity that always delegates to the most recent version of the received function. Lets you register handlers on external listeners (window events, integrations with imperative libraries) without suffering from stale closures and without invalidating deps.

Also exports useIsomorphicEffect, an SSR-safe version of useLayoutEffect.

When to use

✅ Use when…🚫 Avoid when…
  • When you need to register a listener on an imperative API (e.g. addEventListener, observers) that should not be re-attached on every render.
  • When a callback is passed to an effect that has other deps, and you don't want to trigger the effect just because the callback was recreated.
  • For most trivial cases — prefer useCallback.
  • When the function must be "frozen" at creation time (that is not the behavior here).

Signature

const stable = useEventCallback(fn: (...args: any[]) => void);

Example

import { useEventCallback } from '@apollion-dsi/core/hooks';
import { useEffect } from 'react';
 
function Component({ onResize }: { onResize: () => void }) {
  const handler = useEventCallback(onResize);
 
  useEffect(() => {
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, [handler]); // stable identity; the effect runs only once
}

See also