useMemo vs. useEffect + useState

こ雲淡風輕ζ 提交于 2019-12-20 17:32:28

问题


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:

useEffect & useState
const useCalculate = numberProp => {
  const [result, setResult] = useState<number>(null);

  useEffect(() => {
    setResult(expensiveCalculation(numberProp));
  }, [numberProp]);

  return result;
};
useMemo
const useCalculateWithMemo = numberProp => {
  return useMemo(() => {
    return expensiveCalculation(numberProp);
  }, [numberProp]);
};

https://codesandbox.io/s/nkxolxwzkj

Both calculate each time the "prop" changes, where is the "caching" of useMemo kicking in?

What are some real world examples for useMemo?


回答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:

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

Lets suppose numberProp 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 numberProp 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.



来源:https://stackoverflow.com/questions/56028913/usememo-vs-useeffect-usestate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!