DEV Community

Kelley van Evert
Kelley van Evert

Posted on

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)