Skip to content

Instantly share code, notes, and snippets.

@rmdort
Created March 11, 2022 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmdort/206891982a3cd8e89296d969c351ca14 to your computer and use it in GitHub Desktop.
Save rmdort/206891982a3cd8e89296d969c351ca14 to your computer and use it in GitHub Desktop.
Cache a variable across render
import { useRef, useLayoutEffect } from "react";
export const useMemoCompare = <T>(
next: T,
compare: (previous: T | undefined, next: T) => boolean
): T => {
const previousRef = useRef<T>();
const previous = previousRef.current;
const isEqual = compare(previous, next);
useLayoutEffect(() => {
if (!isEqual) previousRef.current = next;
}, [next]);
return isEqual ? previous ?? next : next;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment