ReactJS Hook Pattern ~Latest Ref Pattern~

Published: (January 13, 2026 at 06:01 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Cover image for ReactJS Hook Pattern Latest Ref Pattern

Latest Ref Pattern

  • 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);

  // 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;
Back to Blog

Related posts

Read more »

React Coding Challenge : TypeHead

Zeeshan Ali !ZeeshanAli-0704https://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws...

Fundamentals of react app

Introduction Today we’re going to look at the reasons and uses of the files and folders that are visible when creating a React app. !React app structurehttps:/...