从react-use 库里面学到的 ref用法

原文链接: 从react-use 库里面学到的 ref用法

上一篇: 使用增量矩阵解决同时修改transform导致的冲突问题

下一篇: 从animejs中学到的一些东西

https://github.com/streamich/react-use

有个这东西, useState只拿到一个set方法

up-9c71ebdbcde5b1be0eb4e2b622095bcd5a2.png

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>
  );
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值