UNPKG

755 BJavaScriptView Raw
1import { useReducer } from 'react';
2
3/**
4 * Create a state setter pair for a boolean value that can be "switched".
5 * Unlike `useState(false)`, `useToggleState` will automatically flip the state
6 * value when its setter is called with no argument.
7 *
8 * @param initialState The initial boolean value
9 * @returns A tuple of the current state and a setter
10 *
11 * ```jsx
12 * const [show, toggleShow] = useToggleState(false)
13 *
14 * return (
15 * <>
16 * <button onClick={() => toggleShow()}>
17 * Toggle
18 * <button>
19 *
20 * {show && <strong>Now you can see me</strong>}
21 * </>
22 * )
23 *
24 * ```
25 */
26export default function useToggleState(initialState = false) {
27 return useReducer((state, action) => action == null ? !state : action, initialState);
28}
\No newline at end of file