Skip to content

Instantly share code, notes, and snippets.

@andrewtremblay
Forked from fnky/use-toggle.ts
Created July 26, 2022 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewtremblay/63fb178e7e6fe76ea9a5aa88b22aa77c to your computer and use it in GitHub Desktop.
Save andrewtremblay/63fb178e7e6fe76ea9a5aa88b22aa77c to your computer and use it in GitHub Desktop.
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> = [
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