useFreshTick
Returns a function that invokes the latest void callback after effects run.
About
useFreshTick lets an existing callback call the latest committed version of another void callback. Unlike useFreshCallback, the returned wrapper is recreated on each render.
Example
import { useEffect, useState } from "react";
import { useFreshTick } from "rooks";
export default function IncrementingTimer() {
const [count, setCount] = useState(0);
const increment = useFreshTick(() => setCount((current) => current + 1));
useEffect(() => {
const timer = window.setInterval(increment, 1_000);
return () => window.clearInterval(timer);
// The first wrapper keeps calling the same fresh callback ref.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <p>Count: {count}</p>;
}Parameters
callback: (...args: T[]) => void— required callback. All argument positions share the inferredTtype.
Return value
Returns (...args: T[]) => void. It forwards arguments to the callback stored after the latest passive effect. It does not return the callback's result.
Behavior and lifecycle
The wrapper function has a new identity each render, but wrappers from earlier renders share the stable ref and continue to reach its current callback. Before the passive effect for a commit runs, calls can reach the preceding callback. Exceptions propagate to the caller.
Compatibility and accessibility
The hook is platform-independent and SSR-safe. Clear any timer or subscription that invokes the wrapper; the hook does not own those resources.
Related
- useFreshCallback is preferable when stable function identity or a return value is required.
- useFreshRef exposes the underlying fresh-value pattern.