-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathindex.ts
More file actions
19 lines (16 loc) · 805 Bytes
/
index.ts
File metadata and controls
19 lines (16 loc) · 805 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import type {Dispatch, SetStateAction} from 'react';
import {useCallback, useState} from 'react';
import {useSyncedRef} from '../useSyncedRef/index.js';
export function useFunctionalState<S>(initialState: S | (() => S)): [() => S, Dispatch<SetStateAction<S>>];
export function useFunctionalState<S = undefined>(): [() => S | undefined, Dispatch<SetStateAction<S | undefined>>];
/**
* Like `useState` but instead of raw state, state getter returned.
*/
export function useFunctionalState<S>(
initialState?: S | (() => S),
): [() => S | undefined, Dispatch<SetStateAction<S | undefined>>] {
const [state, setState] = useState(initialState);
const stateRef = useSyncedRef(state);
// eslint-disable-next-line react-hooks/exhaustive-deps
return [useCallback(() => stateRef.current, []), setState];
}