@react-hookz/web
Version:
React hooks done right, for browser and SSR.
31 lines (30 loc) • 1.18 kB
JavaScript
import { useCallback } from 'react';
import { resolveHookState } from "../util/resolveHookState.js";
import { useSafeState } from '..';
/**
* Like `useSafeState`, but can only become `true` or `false`.
*
* State setter, in case called without arguments, will change the state to opposite.
*
* @param initialState Initial toggle state, defaults to false.
*/
export function useToggle(initialState) {
if (initialState === void 0) { initialState = false; }
// We dont use useReducer (which would end up with less code), because exposed
// action does not provide functional updates feature.
// Therefore we have to create and expose our own state setter with
// toggle logic.
var _a = useSafeState(initialState), state = _a[0], setState = _a[1];
return [
state,
useCallback(function (nextState) {
setState(function (prevState) {
if (typeof nextState === 'undefined') {
return !prevState;
}
return Boolean(resolveHookState(nextState, prevState));
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []),
];
}