useMemo vs. useEffect + useState

63,697

Solution 1

The useEffect and setState will cause extra renders on every change: the first render will "lag behind" with stale data and then it'll immediately queue up an additional render with the new data.


Suppose we have:

// Maybe I'm running this on a literal potato
function expensiveCalculation(x) { return x + 1; };

Lets suppose x is initially 0:

  • The useMemo version immediately renders 1.
  • The useEffect version renders null, then after the component renders the effect runs, changes the state, and queues up a new render with 1.

Then if we change x to 2:

  • The useMemo runs and 3 is rendered.
  • The useEffect version runs, and renders 1 again, then the effect triggers and the component reruns with the correct value of 3.

In terms of how often expensiveCalculation runs, the two have identical behavior, but the useEffect version is causing twice as much rendering which is bad for performance for other reasons.

Plus, the useMemo version is just cleaner and more readable, IMO. It doesn't introduce unnecessary mutable state and has fewer moving parts.

So you're better off just using useMemo here.

Solution 2

I think there are two main points you should consider when choosing between them.

  1. Time when function called.

useEffect called after component has been rendered, so you can access DOM from it. For example, this is important if you want to access DOM elements via refs.

  1. Semantic guarantees.

useEffect guarantees that it will not be fired if dependencies have not changed. useMemo does not give such guarantees.

As stated in the React documentation, you should consider useMemo as pure optimization technique. Your program should continue to work correctly even if you replace useMemo with regular function call.

useEffect + useState can be used to control updates. Even to break-up circular dependencies and prevent infinite update loops.

Solution 3

I would say other than the async nature, there might be some difference in terms how they are designed.

useEffect is a collective call, async or not, it's collected after all components are rendered.

useMemo is a local call, which has only something to do with this component. You could just think of useMemo as another assignment statement with benefits to use the assignment from last update.

This means, useMemo is more urgent, and then useLayoutEffect and the last being useEffect.

Share:
63,697

Related videos on Youtube

Bennett Dams
Author by

Bennett Dams

Full Stack, with a love for React & TypeScript.

Updated on April 13, 2022

Comments

  • Bennett Dams
    Bennett Dams about 2 years

    Are there any benefits in using useMemo (e.g. for an intensive function call) instead of using a combination of useEffect and useState?

    Here are two custom hooks that work exactly the same on first sight, besides useMemo's return value being null on the first render:

    See on CodeSandbox

    useEffect & useState

    import { expensiveCalculation } from "foo";
    
    function useCalculate(someNumber: number): number {
      const [result, setResult] = useState<number>(null);
    
      useEffect(() => {
        setResult(expensiveCalculation(someNumber));
      }, [someNumber]);
    
      return result;
    }
    

    useMemo

    import { expensiveCalculation } from "foo";
    
    function useCalculateWithMemo(someNumber: number): number {
        return useMemo(() => {
            return expensiveCalculation(someNumber);
        }, [someNumber]);
    };
    

    Both calculate the result each time their parameter someNumber changes, where is the memoization of useMemo kicking in?

    • Jonas Wilms
      Jonas Wilms about 5 years
      The first will be null on the first render, while the second won't?
    • Estus Flask
      Estus Flask about 5 years
      Are there any benefits in using useMemo (e. g. for an intensive function call) - yes. You're using a hook that was designed specifically for this purpose. The example you listed is most common real world example for useMemo.
  • Mark Adamson
    Mark Adamson over 4 years
    I'm not 100% convinced if this rule would apply to every scenario. I'd like to know and try what would happen if it really was an expensive calc or if it was a network call where you might want to do two renders, one with a spinner and one with the final value. I guess that's what the new Suspense features are all about and perhaps they work fine with useMemo I did try a version, but it doesn't tell me much so I think it needs some rework codesandbox.io/s/usememo-vs-useeffect-usestate-ye6qm
  • Retsam
    Retsam over 4 years
    @MarkAdamson It applies to every scenario in which you are using useEffect to synchronously compute a value and setting it with useState. It doesn't apply for asynchronous situations like where you'd want to show a loading spinner.
  • Mark Adamson
    Mark Adamson over 4 years
    I think the useEffect could be useful in some long running synchronous scenarios too. Check out the sandbox below. It takes 5 seconds to load because of the useMemo holding the render thread while the long calc runs, while the useEffect/useState one can show a 'spinner' while the calc is running so doesn't hold up the render: codesandbox.io/s/usememo-vs-useeffect-usestate-ye6qm @Retsam
  • ecoe
    ecoe over 4 years
    besides optimization, I use useMemo instead of the useState + useEffect pattern because debugging is harder with more renders.
  • M Miller
    M Miller over 4 years
    It’s worth noting that the React API docs mention that useMemo doesn’t guarantee that the memoized function won’t be executed again if the dependencies don’t change because React may, in the future, discard cache to improve performance. So if the memoized function has side effects of some kind, it might be smarter to use a custom hook.
  • Abhi
    Abhi almost 4 years
    Why will it render "1" again when the numberProp changes to 2
  • Retsam
    Retsam almost 4 years
    @Abhi Changing a prop triggers a re-render. But the value that is rendered is based on the [result, setResult] state, and setResult won't be called until the useEffect runs, which happens after the render.
  • Dmitry Davydov
    Dmitry Davydov almost 4 years
    useState can recieve a function to calculate its initial value. So, if there is no need in recalculating memoized value based on props, then useState and useMemo are equal? const [x] = useState(() => calcX()) is equivalent to const x = useMemo(() => calcX(), [])?
  • Retsam
    Retsam almost 4 years
    @DmitryDavydov I think that's true, but if the calcX() calculation doesn't depend on any state or props of your component, you can pull it out the component as a constant and don't need to use a hook at all.
  • bluenote10
    bluenote10 over 3 years
    Can we conclude from this that useEffect + useState is the right solution in situations where the thing to compute is async, because the value cannot be available in the current render anyway? Related question.
  • Retsam
    Retsam over 3 years
    @bluenote10 Yeah, it doesn't generally make sense to memoize the promise itself, so you'd instead want to update state based on the result of the promise.
  • Carmine Tambascia
    Carmine Tambascia over 2 years
    I see as wrote from other above that useMemo suite way better case when there are exteremely expensive calculation that do not depend on states or any side effects, so more for pure "funcions" case
  • Carmine Tambascia
    Carmine Tambascia over 2 years
    @MarkAdamson quite the opposite, is better use useEffect + useState when there is a need of an async code that it's by nature a side effects, meaning his happening outside and you don't know exactly when, as here others have already pointed out stackoverflow.com/questions/61751728/…
  • Mark Adamson
    Mark Adamson over 2 years
    Thanks @CarmineTambascia, it's been a while since I posted that so don't recall the context. But I don't think our statements are contradictory. I was identifying a time when useEffect could be useful for synchronous actions that don't have side effects vs. usememo. It's still the case that useEffect is intended and designed for helping with side effects as you say.