# useEventCallback > A stable callback that always calls the latest closure. - Category: Effects - Package: `hookli` (install with `npm i hookli`) - Docs: https://hookli.vercel.app/docs/use-event-callback ## Signature ```ts useEventCallback(fn: (...args: Args) => R): (...args: Args) => R ``` ## Parameters - `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 - `callback`: `(...args: Args) => R` — A memoized callback with an unchanging identity that always forwards to the latest fn. ## Usage ```tsx import { useState } from "react"; import { useEventCallback } from "hookli"; export function Demo() { const [count, setCount] = useState(0); const readLatest = useEventCallback(() => count); return (
); } ``` ## Source `src/hooks/use-event-callback/use-event-callback.ts` ```ts import { useCallback, useRef } from "react"; import { useIsomorphicLayoutEffect } from "../use-isomorphic-layout-effect/use-isomorphic-layout-effect"; export const useEventCallback = ( 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]); }; ```