Skip to content

Instantly share code, notes, and snippets.

@fnky
Created May 13, 2022 12:29
Show Gist options
  • Save fnky/e6e35ea355a552573e579ca80d7d5837 to your computer and use it in GitHub Desktop.
Save fnky/e6e35ea355a552573e579ca80d7d5837 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