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

perf: 优化useGetState #2417

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/hooks/src/useGetState/demo/demo2.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React, { useEffect } from 'react';
import { useGetState } from 'ahooks';

/**
* desc.zh-CN: setState 之后可以立即获取最新的 state 值
*/
export default () => {
const [count, setCount, getCount] = useGetState<number>(0);

function handleClick() {
setCount(count + 1);
const newCount = getCount();
// do something with newCount
alert(newCount);
}

return <button onClick={handleClick}>add count and alert</button>;
};
7 changes: 6 additions & 1 deletion packages/hooks/src/useGetState/index.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,15 @@ Add a getter method to the return value of `React.useState` to get the latest va

## Examples

### Default usage
### Default usage 1

<code src="./demo/demo1.tsx" />

### Default usage 2

After setState, you can immediately obtain the latest state value
<code src="./demo/demo2.tsx" />

## TypeScript definition

```typescript
Expand Down
12 changes: 10 additions & 2 deletions packages/hooks/src/useGetState/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,20 @@ function useGetState<S = undefined>(): [
];
function useGetState<S>(initialState?: S) {
const [state, setState] = useState(initialState);

const stateRef = useRef(state);
stateRef.current = state;

const setStateWithRef: Dispatch<SetStateAction<S>> = (newValue) => {
setState((cur) => {
const _newValue = typeof newValue === 'function' ? (newValue as any)(cur) : newValue;
stateRef.current = _newValue as S;
return _newValue as S;
});
};

const getState = useCallback(() => stateRef.current, []);

return [state, setState, getState];
return [state, setStateWithRef, getState];
}

export default useGetState;
7 changes: 6 additions & 1 deletion packages/hooks/src/useGetState/index.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,15 @@ nav:

## 代码演示

### 基础用法
### 基础用法 1

<code src="./demo/demo1.tsx" />

### 基础用法 2

setState 之后可以立即获取最新的 state 值
<code src="./demo/demo2.tsx" />

## 类型定义

```typescript
Expand Down