useLatest
Always-current ref — kills stale closures.
Import
TypeScript
import { useLatest } from '@/hooks';API
Signature
useLatest<T>(value) → MutableRefObject<T>
When to use
Use useLatest instead of re-implementing the same pattern in multiple components.
SSR / Next.js
SSR-safe. Timers and rAF only run after mount / interactions.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useLatestEditor
function Poll({ onTick }: { onTick: () => void }) { const latest = useLatest(onTick); useEffect(() => { const id = setInterval(() => latest.current(), 1000); return () => clearInterval(id); }, [latest]); return null; }
Preview
Implementation source
Full library source for useLatest — copy into your project when you are not installing a package yet.
hooks/performance/useLatest.ts
export { useLatest } from '../utility/useLatest';
Copy-paste example
useLatest.example.tsx
'use client';
import { useEffect } from 'react';
import { useLatest } from '@/hooks';
export function Poll({ onTick }: { onTick: () => void }) {
const latest = useLatest(onTick);
useEffect(() => {
const id = setInterval(() => latest.current(), 1000);
return () => clearInterval(id);
}, [latest]);
return null;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Stable callbacks prevent child re-renders. Always cancel debounce on unmount (handled for you).
- Source of truth: open
hooks/performance/useLatest.tsfor implementation details