Skip to the content

useEventCallback

useEventCallback returns a function with a stable identity that always calls the latest version of the function you pass. Use it for listeners on imperative APIs (addEventListener, observers) that should not re-attach on every render. The module also exports useIsomorphicEffect: useLayoutEffect in the browser, useEffect on the server.
Hooks

Signature

const stable = useEventCallback(fn: (...args: any[]) => void);
Name
Type
Description
fn
(...args: any[]) => void
The function to call. It may change on every render.
returns
stable function
Same identity for the component's whole life.
Scrolls sideways inside the table. The page does not.

Example

import { useEffect } from 'react';
import { useEventCallback } from '@apollion-dsi/core/hooks';

function ResizeListener({ onResize }: { onResize: () => void }) {
  const handler = useEventCallback(onResize);

  useEffect(() => {
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, [handler]);

  return null;
}

Pitfalls

  • The latest fn is stored in a layout effect. Call the stable function from events and effects, not during render.
  • The return type is any: type the call site yourself.
  • For a callback passed straight to a child, useCallback is usually enough.

See also