You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import{useCallback,useEffect,useMemo,useState}from"react";functionUseCallbackAndUseMemo(){const[a,setA]=useState('a');const[b]=useState('b');constmemoizedCallback=useCallback(()=>{console.log(a,b);},[a,b],);constmemoizedResult=useMemo(()=>{return{
a,
b
}},[a,b]);useEffect(()=>{setTimeout(()=>{setA('aaa');},3000);},[]);useEffect(()=>{console.log(memoizedResult,'memoizedResult change');},[memoizedResult]);return(<divonClick={memoizedCallback}>click here</div>)}exportdefaultUseCallbackAndUseMemo;
React Hooks: useCallback & useMemo
说明
useCallback
mount 阶段的 useCallback
对 useCallback 打上断点,会进入 mountCallback
来康康里面是什么东西
没了。。。那就再看看 update 干了啥
update 阶段的 useCallback
保持断点不变,等定时器执行,随后进入 updateCallback
来康康里面是什么东西
大致上就是通过比较前后依赖项来决定是否复用上一次缓存的函数,一个类似闭包的实现。举例来解释的话,类似下面的代码。
当两个函数都传入同一个值时,虽然都会得到执行结果都为 4 的函数,但是 func1 与 func2 绝不是同一个函数。如果传入到 react 的组件内必然会导致 props 发生变化从而导致重新渲染组件,但即使重新渲染后,页面也不会发生变化。所以为了防止出现没有必要的重渲染,索性就用了执行结果相同的缓存函数。
接下来看看 areHookInputsEqual 是怎么比较前后依赖的
useCallback 总结
useCallback 通过将函数与依赖存入到对应的 hook 对象上,在更新时会通过对前后依赖进行一一的浅比较来判断函数是否可以复用,从而来实现复用函数,避免组件发生不必要的更新。
useMemo
mount 阶段的 useMemo
对 useMemo 打点,会进入 mountMemo
update 阶段的 useMemo
保持断点不变,等定时器执行,随后进入 updateMemo
还是和 useCallback 的 update 阶段一模一样的逻辑。不讲了。
useMemo 总结
useMemo 与 useCallback 的实现几乎一致,唯一的不同是,useMemo 存储函数运行后的结果,useCallback 则是存储函数本身。
The text was updated successfully, but these errors were encountered: