・The latest ref pattern solves the problem of accessing the latest values in useEffect without having to add them to the dependency array. First, you create a ref to store the function, then another useEffect with no dependencies that runs on every render to keep the ref updated.
import { useEffect, useRef } from "react";
function ClickHandler({ onClick }) {
const onClickRef = useRef(onClick);
useEffect(() => {
onClickRef.current = onClick
})
useEffect(() => {
const handleClick = () => {
onClickRef.current();
};
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
}, []);
return (
<div>
<h1>Latest Ref Pattern</h1>
</div>
);
}
function App() {
return <ClickHandler onClick={() => console.log("Clicked")} />;
}
export default App;
Top comments (0)