UNPKG

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