Skip to content

Instantly share code, notes, and snippets.

Created May 13, 2022 12:29
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Simple toggle hook using useReducer w/ types for reducer with optional action.
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> = [
function useToggle(
initialState: boolean = false
): ReducerValueWithOptionalAction<boolean> {
return React.useReducer<ReducerWithOptionalAction<boolean>>(
(prev, override) => override ?? !prev,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment