Skip to content

Commit

Permalink
refactor: update
Browse files Browse the repository at this point in the history
  • Loading branch information
liuyib committed Jun 4, 2024
1 parent 42e6002 commit 67e106b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 24 deletions.
43 changes: 22 additions & 21 deletions packages/hooks/src/useResetState/demo/demo1.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,37 @@
import React, { useRef } from 'react';
import React, { useMemo } from 'react';
import { Button, Space } from 'antd';
import { useResetState } from 'ahooks';

interface State {
hello: string;
value: number;
}

export default () => {
const initialValue = useRef({
const initialValue = {
hello: '',
value: Math.random(),
}).current;
};
const initialValueMemo = useMemo(() => {
return initialValue;
}, []);

const [state, setState, resetState] = useResetState<State>(() => initialValue);
const [state, setState, resetState] = useResetState(initialValue);

return (
<div>
<div>initial state: </div>
<pre>{JSON.stringify(initialValueMemo, null, 2)}</pre>
<div>current state: </div>
<pre>{JSON.stringify(state, null, 2)}</pre>
<div>initialValue: {JSON.stringify(initialValue, null, 2)}</div>
<p>
<button
type="button"
style={{ marginRight: '8px' }}
onClick={() => setState(() => ({ hello: 'world', value: Math.random() }))}
<Space>
<Button
onClick={() =>
setState(() => ({
hello: 'world',
value: Math.random(),
}))
}
>
set hello and value
</button>

<button type="button" onClick={resetState}>
resetState
</button>
</p>
</Button>
<Button onClick={resetState}>resetState</Button>
</Space>
</div>
);
};
8 changes: 5 additions & 3 deletions packages/hooks/src/useResetState/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { useState } from 'react';
import { useRef, useState } from 'react';
import type { Dispatch, SetStateAction } from 'react';
import useMemoizedFn from '../useMemoizedFn';
import { isFunction } from '../utils';
import useMemoizedFn from '../useMemoizedFn';
import useCreation from '../useCreation';

type ResetState = () => void;

const useResetState = <S>(
initialState: S | (() => S),
): [S, Dispatch<SetStateAction<S>>, ResetState] => {
const initialStateRef = useRef(initialState);
const initialStateMemo = useCreation(
() => (isFunction(initialState) ? initialState() : initialState),
() =>
isFunction(initialStateRef.current) ? initialStateRef.current() : initialStateRef.current,
[],
);

Expand Down

0 comments on commit 67e106b

Please sign in to comment.