Created
March 11, 2022 15:35
-
-
Save rmdort/206891982a3cd8e89296d969c351ca14 to your computer and use it in GitHub Desktop.
Cache a variable across render
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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