原文链接: 从react-use 库里面学到的 ref用法
上一篇: 使用增量矩阵解决同时修改transform导致的冲突问题
下一篇: 从animejs中学到的一些东西
https://github.com/streamich/react-use
有个这东西, useState只拿到一个set方法
ref的更新不会触发重新渲染, 但是重新渲染会把ref的最新值更新到ui上
import React, { useRef, useState } from "react";
export default () => {
const cRef = useRef(0);
const [cState, set] = useState(0);
return (
<div>
ref:{cRef.current}
state:{cState}
<button onClick={() => cRef.current++}>ref++</button>
<button onClick={() => set((v) => v + 1)}>state++</button>
</div>
);
};
官方demo也是很秀啊
第一次挂载触发重新渲染, 如果不是深比较最后结果是500, 深比较只会更新一次, 因为options每次在重新渲染的时候都是创建的新对象
const Demo = () => {
const [countNormal, { inc: incNormal }] = useCounter(0);
const [countDeep, { inc: incDeep }] = useCounter(0);
const options = { max: 500 };
React.useEffect(() => {
if (countNormal < options.max) {
incNormal();
}
}, [options]);
useDeepCompareEffect(() => {
if (countNormal < options.max) {
incDeep();
}
}, [options]);
return (
<div>
<p>useEffect: {countNormal}</p>
<p>useDeepCompareEffect: {countDeep}</p>
</div>
);
};