useMemo
and useCallback
with a stable cache (semantic guarantee)
useMemo
and useCallback
cache the most recent result. However, this cache can be destroyed by React
when it wants to:
You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance. - React docs
useMemoOne
and useCallbackOne
are concurrent mode
safe alternatives to useMemo
and useCallback
that do provide semantic guarantee. What this means is that you will always get the same reference for a memoized value so long as there is no input change.
Using useMemoOne
and useCallbackOne
will consume more memory than useMemo
and useCallback
in order to provide a stable cache.
# npm
npm install use-memo-one --save
# yarn
yarn add use-memo-one
import { useMemoOne, useCallbackOne } from 'use-memo-one';
function App(props) {
const { name, age } = props;
const value = useMemoOne(() => ({hello: name}), [name]);
const getAge = useCallbackOne(() => age, [age])
// ...
}
See useMemo
and useCallback