-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathuseState.ts
More file actions
40 lines (33 loc) · 1.04 KB
/
useState.ts
File metadata and controls
40 lines (33 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import * as React from 'react';
type Updater<T> = T | ((prevValue: T) => T);
export type SetState<T> = (
nextValue: Updater<T>,
/**
* Will not update state when destroyed.
* Developer should make sure this is safe to ignore.
*/
ignoreDestroy?: boolean,
) => void;
/**
* Same as React.useState but `setState` accept `ignoreDestroy` param to not to setState after destroyed.
* We do not make this auto is to avoid real memory leak.
* Developer should confirm it's safe to ignore themselves.
*/
const useSafeState = <T>(defaultValue?: T | (() => T)): [T, SetState<T>] => {
const destroyRef = React.useRef<boolean>(false);
const [value, setValue] = React.useState(defaultValue);
React.useEffect(() => {
destroyRef.current = false;
return () => {
destroyRef.current = true;
};
}, []);
function safeSetState(updater: Updater<T>, ignoreDestroy?: boolean) {
if (ignoreDestroy && destroyRef.current) {
return;
}
setValue(updater);
}
return [value, safeSetState];
};
export default useSafeState;