hooks icon indicating copy to clipboard operation
hooks copied to clipboard

feat: add useRefState hooks

Open maxiaokai1996 opened this issue 2 years ago • 8 comments

处理闭包问题,在useState的基础上多了一个获取最新state的函数

To deal with the closure problem, there is an additional function to get the latest state on the basis of useState

maxiaokai1996 avatar Oct 26 '23 08:10 maxiaokai1996

CLA assistant check
All committers have signed the CLA.

CLAassistant avatar Oct 26 '23 08:10 CLAassistant

Could u provide some usage of this hook?

kongmoumou avatar Oct 30 '23 16:10 kongmoumou

@kongmoumou Of course, this hook mainly solves the problem of providing a channel inside the function closure to get the latest state value. Kind of like a combination of useState and useLatest。But his update time is earlier than useLatest, can guarantee the latest value。

demo:

import React, { useEffect } from 'react';
import { useStateRef } from 'ahooks';


export default () => {
  const [value, setValue, getValue] = useStateRef(false);

  useEffect(() => {
    setTimeout(() => {
      setValue('data loaded from server');
    }, 5000);

    setTimeout(() => {
      console.log(getValue());
    }, 6000);
  }, []);

  const text = value || 'Loading...';

  return <div>{text}</div>;
};

maxiaokai1996 avatar Nov 03 '23 04:11 maxiaokai1996

https://github.com/streamich/react-use/blob/master/docs/useGetSet.md

SignDawn avatar Nov 03 '23 15:11 SignDawn

相关 issue:https://github.com/alibaba/hooks/issues/2266

#2266 对应的 PR 会有 breaking changes。建议废弃掉 useGetState,引入这个 hook

mark 一下

liuyib avatar Nov 06 '23 02:11 liuyib

好的,我完善一下

maxiaokai1996 avatar Nov 06 '23 04:11 maxiaokai1996

@liuyib 相关调整已同步

maxiaokai1996 avatar Nov 06 '23 06:11 maxiaokai1996