Search code examples
javascriptreactjsmemoizationreact-usememo

How can I persistently memoize across renders of a React component?


I'm using React with hooks. I have an expensive function that I'd like to memoize.

I know React comes with useMemo(), but the values I need memoized are calculated once, each, on their first render. So there's no point to memoization within the first render, but memoization in future renders would be beneficial.

I've read the useMemo() documentation but it doesn't provide a firm answer So: do the values stored in useMemo() persist across re-renders of the component calling useMemo?

How can I persistently memoize across different renders of a React component?


Solution

  • const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
    

    Let's say above line of code is within ComponentA. Now, assuming that ComponentA hasn't been unmounted, then, memoizedValue persists across re renders given also that dependencies (a, b) don't change across re renders.

    Also react docs say in the future react may decide to forget the memoized value sometimes so one should use it for optimization not as semantic guarantee.