-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
22 lines (19 loc) · 850 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { Dispatch, SetStateAction, useCallback, useState } from 'react';
/**
* Returns a stateful value, and a functions to set and update it.
*/
export function usePartialState<S>(initialValue: S): [S, Dispatch<SetStateAction<S>>, (updated: Partial<S>) => void];
export function usePartialState<S = undefined>(
initialValue?: S
): [S | undefined, Dispatch<SetStateAction<S | undefined>>, (updated: Partial<S>) => void];
export function usePartialState<S>(
initialValue?: S
): [S | undefined, Dispatch<SetStateAction<S | undefined>>, (updated: Partial<S>) => void] {
const [state, setState] = useState(initialValue);
const partialSetState = useCallback((updated: Partial<S>) => {
setState(prev => {
return prev ? { ...prev, ...updated } : ({ ...updated } as S);
});
}, []);
return [state, setState, partialSetState];
}