DEV Community

Kelley van Evert
Kelley van Evert

Posted on

1

A helper hook to remember values by deep equality

So of course every React hook enthusiast will have had a use-case for a deep (structural) equality check on the dependencies argument, at a certain point in time. Instead of crafting these things every time you need them, or importing a helper library, here's a wonderfully simple helper hook to help you out:

import { useRef } from "react";
import isEqual from "react-fast-compare";

export default function remember<T>(value: T): T {
  const ref = useRef<T>(value);
  if (!isEqual(value, ref.current)) {
    ref.current = value;
  }
  return ref.current;
}

You can use it like this:

const something = useMemo(expensiveComputation, [ remember(input) ]);

Isn't that just lovely? :D

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay