ReactJS Hook Pattern ~Latest Ref Pattern~
Published: (January 13, 2026 at 06:01 PM EST)
1 min read
Source: Dev.to
Source: Dev.to

Latest Ref Pattern
- The latest ref pattern solves the problem of accessing the latest values in
useEffectwithout having to add them to the dependency array. - First, you create a ref to store the function, then another
useEffectwith no dependencies that runs on every render to keep the ref updated.
import { useEffect, useRef } from "react";
function ClickHandler({ onClick }) {
const onClickRef = useRef(onClick);
// Keep the ref up‑to‑date on every render
useEffect(() => {
onClickRef.current = onClick;
});
// Use the ref inside an effect with an empty dependency array
useEffect(() => {
const handleClick = () => {
onClickRef.current();
};
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
}, []);
return (
// JSX for the component can be placed here
);
}
function App() {
return <ClickHandler onClick={() => console.log("Clicked")} />;
}
export default App;