useEventCallback
The useEventCallback hook returns a function with a stable identity that always calls the latest version of your callback. It gives you the best of both worlds: handlers that never change (so memoized children and effects do not re-run) and no stale props or state inside them.
Usage
Installation
import { useEventCallback } from "hookstorm";
Parameters
- callback — The function to wrap. It may take any arguments and return any value.
Return Values
A stable function with the same signature as callback. It never changes between renders.
Example Usage
import { ReactElement, memo, useState } from "react";
import { useEventCallback } from "hookstorm";
const ExpensiveButton = memo(function ExpensiveButton({
onClick,
}: {
onClick: () => void;
}): ReactElement {
console.log("ExpensiveButton rendered");
return <button onClick={onClick}>Log count</button>;
});
export default function Counter(): ReactElement {
const [count, setCount] = useState(0);
// Same function on every render, but it always sees the latest `count`
const logCount = useEventCallback(() => console.log("count is", count));
return (
<div>
<button onClick={() => setCount((c) => c + 1)}>Count: {count}</button>
<ExpensiveButton onClick={logCount} />
</div>
);
}
Notes
- Do not call the returned function during render — only from event handlers, effects, or other callbacks.
- Unlike
useCallback, there is no dependency array to maintain. - Because the identity never changes, the function is safe to omit from the dependency array of effects.