Skip to main content

Function: useEventCallback()

@arolariu/components


@arolariu/components / useEventCallback

Function: useEventCallback()

useEventCallback<Args, Return>(callback): (...args) => Return

Defined in: hooks/useEventCallback.tsx:37

Creates a stable callback reference that always calls the latest version of the provided function.

Type Parameters

Args

Args extends unknown[]

The tuple type of the callback's arguments.

Return

Return

The return type of the callback.

Parameters

callback

(...args) => Return

The function to wrap with a stable reference.

Returns

A stable function reference that invokes the latest callback.

(...args) => Return

Remarks

Unlike useCallback, this hook returns a stable function reference that never changes, but always invokes the most recent version of the callback. This is useful when you need to pass callbacks to optimized child components or effects without triggering re-renders when dependencies change.

The returned function is safe to use in dependency arrays because its identity never changes.

Example

function SearchInput({onSearch}) {
const [query, setQuery] = useState("");
// stableOnSearch never changes identity, but always calls the latest onSearch
const stableOnSearch = useEventCallback(onSearch);

useEffect(() => {
const timer = setTimeout(() => stableOnSearch(query), 500);
return () => clearTimeout(timer);
}, [query, stableOnSearch]); // Safe to include in deps

return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
// was this page useful?