Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useMemo和React.memo,记住:要用useMemo,必须有依赖项 #14

Open
wangmeijian opened this issue Sep 29, 2022 · 0 comments
Open

Comments

@wangmeijian
Copy link
Owner

React日常开发中,有两种方式缓存渲染结果,useMemoReact.memo,他们的区别只需要记住一句话:要用useMemo,必须有依赖项。

useMemoReact.memo,看看他们分别适用于什么场景。

useMemo

useMemo属于React hookReact hook并不是在所有地方都能使用的,它只能在组件顶层或hook内部调用

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

useMemo返回一个记忆值,只有当它的依赖项改变时,才重新计算返回值

React.memo

React.memo则属于HOC(高阶组件),如果你希望你的组件只有在props变化的情况下,才重新渲染,就可以使用React.memo包装你的组件,然后再调用

const MyComponent = React.memo(function MyComponent(props) {
  // 只有props变化,才会重新渲染
});

举例

只看原理和概念,理解是浅薄的,结合一个最简单的例子就非常容易理解了。

初始状态:父组件Parent更新时间戳,子组件Child每次都重新渲染,Demo

React.memo包装Child组件,再点击更新时间戳,Child不会重新渲染

const ChildHOC = React.memo(Child);

<ChildHOC />

用useMemo处理

function Child() {
	const renderCount = useRef(0);
	
	return useMemo(() => <div>子组件渲染次数:{renderCount.current++}</div>),[]);
}

会发现,Child还是会重新渲染,因为如果没有提供依赖项数组,useMemo在每次渲染时都会计算新的值

那么给Child组件加上依赖试试看,Demo

此时,只有当Childprops变化,Child才会重新渲染

总结

想让组件只在props变化时重新渲染,用React.memo

想让组件只在依赖项变化时重新渲染,用useMemo前提是组件必须有依赖项

最后,通篇只需要记住一句话:要用useMemo,必须有依赖项

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant