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

feat: add useRefState hooks #2348

Open
wants to merge 8 commits into
base: master
Choose a base branch
from

Conversation

maxiaokai1996
Copy link

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

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

@CLAassistant
Copy link

CLAassistant commented Oct 26, 2023

CLA assistant check
All committers have signed the CLA.

@liuyib liuyib marked this pull request as draft October 30, 2023 02:19
@kongmoumou
Copy link
Contributor

Could u provide some usage of this hook?

@maxiaokai1996 maxiaokai1996 marked this pull request as ready for review November 3, 2023 03:53
@maxiaokai1996
Copy link
Author

maxiaokai1996 commented Nov 3, 2023

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

@SignDawn
Copy link

SignDawn commented Nov 3, 2023

@liuyib
Copy link
Collaborator

liuyib commented Nov 6, 2023

相关 issue:#2266

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

mark 一下

@maxiaokai1996
Copy link
Author

好的,我完善一下

@maxiaokai1996
Copy link
Author

@liuyib 相关调整已同步

@liuyib liuyib self-requested a review November 6, 2023 07:33
@liuyib liuyib changed the title feat: 新增useStateRef hooks feat: add useRefState hooks Nov 6, 2023
@liuyib liuyib mentioned this pull request Nov 15, 2023
@liuyib liuyib mentioned this pull request Dec 26, 2023
18 tasks
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

Successfully merging this pull request may close these issues.

5 participants