forked from Aminadav/react-useStateRef
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
29 lines (21 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
29
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 UseStateRefValue<T> = [T, Dispatch<SetStateAction<T>>, ReadOnlyRefObject<T>];
type UseStateRef = {
<S>(initialState: S | (() => S)): UseStateRefValue<S>;
<S = undefined>(): UseStateRefValue<S>;
};
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] as UseStateRefValue<S>;
};
export = useStateRef;