|
| 1 | +import { Dispatch, SetStateAction, useCallback } from 'react' |
| 2 | +import useMounted from './useMounted' |
| 3 | +import { AsyncSetState } from './useStateAsync' |
| 4 | + |
| 5 | +type StateSetter<TState> = Dispatch<SetStateAction<TState>> |
| 6 | + |
| 7 | +/** |
| 8 | + * `useSafeState` takes the return value of a `useState` hook and wraps the |
| 9 | + * setter to prevent updates onces the component has unmounted. Can used |
| 10 | + * with `useMergeState` and `useStateAsync` as well |
| 11 | + * |
| 12 | + * @param state The return value of a useStateHook |
| 13 | + * |
| 14 | + * ```ts |
| 15 | + * const [show, setShow] = useSafeState(useState(true)); |
| 16 | + * ``` |
| 17 | + */ |
| 18 | +function useSafeState<TState>( |
| 19 | + state: [TState, AsyncSetState<TState>], |
| 20 | +): [TState, (stateUpdate: React.SetStateAction<TState>) => Promise<void>] |
| 21 | +function useSafeState<TState>( |
| 22 | + state: [TState, StateSetter<TState>], |
| 23 | +): [TState, StateSetter<TState>] |
| 24 | +function useSafeState<TState>( |
| 25 | + state: [TState, StateSetter<TState> | AsyncSetState<TState>], |
| 26 | +): [TState, StateSetter<TState> | AsyncSetState<TState>] { |
| 27 | + const isMounted = useMounted() |
| 28 | + |
| 29 | + return [ |
| 30 | + state[0], |
| 31 | + useCallback( |
| 32 | + (nextState: SetStateAction<TState>) => { |
| 33 | + if (!isMounted()) return |
| 34 | + return state[1](nextState) |
| 35 | + }, |
| 36 | + [isMounted, state[1]], |
| 37 | + ), |
| 38 | + ] |
| 39 | +} |
| 40 | + |
| 41 | +export default useSafeState |
0 commit comments