Effects
useEventCallback
A stable callback that always calls the latest closure.
Demo
live · imported from hookli
0
- captured
- —
- callback identity
- stable
import { useState } from "react";
import { useEventCallback } from "hookli";
export function Demo() {
const [count, setCount] = useState(0);
const readLatest = useEventCallback(() => count);
return (
<div>
<button onClick={() => setCount((prev) => prev + 1)}>{count}</button>
<button onClick={() => alert(readLatest())}>Read latest</button>
</div>
);
}Usage
import { useState } from "react";
import { useEventCallback } from "hookli";
export function Demo() {
const [count, setCount] = useState(0);
const readLatest = useEventCallback(() => count);
return (
<div>
<button onClick={() => setCount((prev) => prev + 1)}>{count}</button>
<button onClick={() => alert(readLatest())}>Read latest</button>
</div>
);
}API
useEventCallback<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => RParameters
| Name | Type | Default | Description |
|---|---|---|---|
| fn | (...args: Args) => R | — | The function to keep current behind a stable reference. Calling during render throws — it is meant for event handlers and effects. |
Returns
| Name | Type | Description |
|---|---|---|
| callback | (...args: Args) => R | A memoized callback with an unchanging identity that always forwards to the latest fn. |
Hook
The implementation, straight from hookli. Copy it, or install the package.
import { useCallback, useRef } from "react";
import { useIsomorphicLayoutEffect } from "../use-isomorphic-layout-effect/use-isomorphic-layout-effect";
export const useEventCallback = <Args extends unknown[], R>(
fn: (...args: Args) => R,
) => {
const ref = useRef<(...args: Args) => R>(() => {
throw new Error("Cannot call an event handler while rendering.");
});
useIsomorphicLayoutEffect(() => {
ref.current = fn;
}, [fn]);
return useCallback((...args: Args) => ref.current(...args), [ref]);
};