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 #20

Open
lazyken opened this issue Jul 7, 2020 · 0 comments
Open

useMemo #20

lazyken opened this issue Jul 7, 2020 · 0 comments

Comments

@lazyken
Copy link
Owner

lazyken commented Jul 7, 2020

先举个例子:

import React,{useState, useMemo} from 'react'

export default function Demo() {
	const [times,setTimes] = useState(1000)
	const sum = useMemo(function computeSum(){
		let sum = 0
		for(let i=0;i<times;i++){
			sum += i
		}
		return sum
	},[times])
	return (
		<div>{sum}</div>
	)
}

这是一个简单的求和Demo,它的工作流程如下:

1、调用setTimes更新times
2、Demo组件重新渲染
3、在渲染过程中,useMemo会比较依赖项times是否改变,如果改变会重新走一遍computeSum计算 sum。如果依赖项times没有改变(与之前的值相等),则不会再sum的值。在例子中即省略了再次计算1000次的计算。

如果对比VUE的话,可以认为相当于computed的作用

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