Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
useStableMemo
import { DependencyList, useState, useEffect, useRef } from 'react';
// use this instead of useMemo of you need a stable value
// see https://twitter.com/0xca0a/status/1314326386555924480
export function useStableMemo<T>(factory: () => T, deps: DependencyList): T {
const [value, setValue] = useState<T>(factory);
const firstRun = useRef(true);
useEffect(
() => {
if (firstRun.current) {
firstRun.current = false;
} else {
setValue(factory);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
deps
);
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment