-
Notifications
You must be signed in to change notification settings - Fork 94
/
index.ts
41 lines (38 loc) · 1.45 KB
/
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
30
31
32
33
34
35
36
37
38
39
40
41
import {type Dispatch, useCallback, useState} from 'react';
import {useSyncedRef} from '../useSyncedRef/index.js';
import {type InitialState, type NextState, resolveHookState} from '../util/resolve-hook-state.js';
export function useMediatedState<State = undefined>(): [
State | undefined,
Dispatch<NextState<State | undefined>>,
];
export function useMediatedState<State>(
initialState: InitialState<State>
): [State, Dispatch<NextState<State>>];
export function useMediatedState<State, RawState = State>(
initialState: InitialState<State>,
mediator?: (state: RawState) => State
): [State, Dispatch<NextState<RawState, State>>];
/**
* Like `useState`, but every value set is passed through a mediator function.
*/
export function useMediatedState<State, RawState = State>(
initialState?: InitialState<State>,
mediator?: (state: RawState | State | undefined) => State,
): [State | undefined, Dispatch<NextState<RawState, State | undefined>>] {
const [state, setState] = useState(() => mediator ? mediator(resolveHookState(initialState)) : initialState);
const mediatorRef = useSyncedRef(mediator);
return [
state as State,
useCallback((value) => {
if (mediatorRef.current) {
setState(previousState =>
mediatorRef.current?.(
resolveHookState<RawState, State | undefined>(value, previousState as State),
));
} else {
setState(value as unknown as State);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []),
];
}