Skip to main content
useEffectEvent is designed to approximate the behavior of React’s experimental useEffectEvent hook. It provides a stable function reference that can be safely used in effect dependencies while always executing with the latest props and state.

Installation

Function Signature

Parameters

T
The callback function to be wrapped. The returned function will always call the latest version of this callback.

Return Value

T
A stable function reference that always calls the latest version of the provided callback. Safe to use in effect dependencies without causing re-runs.

Usage

Basic Example

Avoiding Stale Closures

Event Handlers in Effects

With External APIs

Implementation Details

The hook has three implementation strategies:
  1. React’s native useEffectEvent (when available in future React versions)
  2. useInsertionEffect for React 18+ (when available)
  3. useLayoutEffect as a fallback for older React versions
The implementation:
  • Stores the callback in a ref
  • Updates the ref before layout/paint using the most appropriate hook
  • Returns a stable memoized function that calls the latest callback
  • Throws an error if called during render

Notes

This is a shim/polyfill for React’s experimental useEffectEvent hook. When React’s official version becomes stable, this hook will automatically use the native implementation.
The returned function cannot be called during render - it will throw an error if you try. It’s designed specifically for use in effects, event handlers, and callbacks.
This hook is similar to useCallbackRef but is specifically designed for the effect event pattern where you want the latest closure without re-running effects.
For more context, see the React RFC for useEffectEvent.