Simple toggle hook using useReducer w/ types for reducer with optional action.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
type ReducerWithOptionalAction<S> = (prevState: S, action?: S) => S; | |
type ReducerStateWithOptionalAction<S> = React.ReducerState<ReducerWithOptionalAction<S>>; | |
type DispatchWithOptionalAction<S> = React.Dispatch<S> & React.DispatchWithoutAction; | |
type ReducerValueWithOptionalAction<S> = [ | |
ReducerStateWithOptionalAction<S>, | |
React.DispatchWithOptionalAction<S>, | |
]; | |
function useToggle( | |
initialState: boolean = false | |
): ReducerValueWithOptionalAction<boolean> { | |
return React.useReducer<ReducerWithOptionalAction<boolean>>( | |
(prev, override) => override ?? !prev, | |
initialState | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment