How to Fix useCallback with Stable Refs
DodaTech
Updated 2026-06-26
1 min read
The Problem
In this quick-fix, you'll learn how to use useCallback with refs for stable references. This matters because unstable function references break memoization. In real-world applications, this pattern appears in event handlers for memoized children callback refs custom hooks.
The Wrong Way
function SearchForm({ onSearch }) {
const [query, setQuery] = useState("");
const handleSubmit = useCallback(() => { onSearch(query); }, []);
return <form onSubmit={handleSubmit}><input value={query} onChange={e=>setQuery(e.target.value)}/></form>;
}
handleSubmit always uses initial query value -- stale closure
The Right Way
function SearchForm({ onSearch }) {
const [query, setQuery] = useState("");
const handleSubmit = useCallback(() => { onSearch(query); }, [query, onSearch]);
return <form onSubmit={handleSubmit}><input value={query} onChange={e=>setQuery(e.target.value)}/></form>;
}
handleSubmit uses latest query stable when deps dont change
Prevention
- Include all reactive values in useCallback deps
- Use useCallback for functions passed to memo children
- Use refs for values that shouldnt trigger recreation
FAQ
This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro