-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.ts
28 lines (20 loc) · 929 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
23
24
25
26
27
28
import { useCallback, useRef, useState, SetStateAction, Dispatch } from "react";
const isFunction = <S>(setStateAction: SetStateAction<S>): setStateAction is (prevState: S) => S =>
typeof setStateAction === "function";
type ReadOnlyRefObject<T> = {
readonly current: T;
};
type UseStateRef = {
<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>, ReadOnlyRefObject<S>];
<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>, ReadOnlyRefObject<S | undefined>];
};
const useStateRef: UseStateRef = <S>(initialState?: S | (() => S)) => {
const [state, setState] = useState(initialState);
const ref = useRef(state);
const dispatch: typeof setState = useCallback((setStateAction:any) => {
ref.current = isFunction(setStateAction) ? setStateAction(ref.current) : setStateAction;
setState(ref.current);
}, []);
return [state, dispatch, ref];
};
export = useStateRef;