反应:useEffect vs useMemo vs useState [英] React: useEffect vs useMemo vs useState
问题描述
我试图在网上找到一个简洁的答案,但是没有运气.
关于 useEffect
, useMemo
和 useState
之间的区别,以下说法正确吗?
- 两者
useState
和useMemo
都会记住渲染中的值.区别在于:-
useMemo
不会引起重新渲染,而useState
会导致 -
useMemo
仅在其依赖项(如果有)更改时运行,而setSomeState
(useState
返回的第二个数组项)不具有这样的依赖项数组
-
- 两者
useMemo
和useEffect
仅在它们的依存关系更改时运行(如果有).区别在于:-
useEffect
在渲染发生后运行,而useMemo
在之前运行
-
我错过了其他重要区别吗?
您的观点基本上是正确的,需要一些澄清:
useState 导致对setState方法的调用(返回的数组中的第二个元素)重新呈现.它没有诸如useMemo或useEffect之类的任何依赖项.
useMemo 仅在其依赖项数组中的元素发生更改时才重新计算一个值(如果没有依赖项,即该数组为空,则将仅重新计算一次).如果忽略该数组,它将在每次渲染时重新计算.调用该函数不会导致重新渲染.此外,它会在组件呈现期间运行,而不是在之前运行.
如果每个p < useEffect 在其渲染数组中的元素已更改或该数组被忽略,则在每个渲染之后称为.如果该数组为空,则它将仅在初始安装时运行一次(如果您返回清除函数,则将其卸载).您随时可以查看 Hooks API参考,这是我的一个非常扎实的文档意见
I was trying to find a concise answer to this on the web without luck.
Is the following correct regarding the differences between useEffect
, useMemo
and useState
?
- Both
useState
anduseMemo
will remember a value across renders. The difference is that:useMemo
does not cause a re-render, whileuseState
doesuseMemo
only runs when its dependencies (if any) have changed, whilesetSomeState
(second array item returned byuseState
) does not have such a dependency array
- Both
useMemo
anduseEffect
only runs when their dependencies change (if any). The difference is that:useEffect
runs after a render happens, whileuseMemo
runs before
Any other key differences I have missed?
Your points are basically correct, some minor clarification:
useState is causing a re-render on the call of the setState method (second element in the array returned). It does not have any dependencies like useMemo or useEffect.
useMemo only recalculates a value if the elements in its dependency array change (if there are no dependencies - i.e. the array is empty, it will recalculate only once). If the array is left out, it will recalculate on every render. Calling the function does not cause a re-render. Also it runs during the render of the component and not before.
useEffect is called after each render, if elements in its dependency array have changed or the array is left out. If the array is empty, it will only be run once on the initial mount (and unmount if you return a cleanup function).
You can always check Hooks API Reference, which is a pretty solid documentation in my opinion
这篇关于反应:useEffect vs useMemo vs useState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!