Skip to content

Instantly share code, notes, and snippets.

@jfamousket
Last active January 26, 2020 19:19
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 jfamousket/c8f04240d783cba48e15fb6ef4876094 to your computer and use it in GitHub Desktop.
Save jfamousket/c8f04240d783cba48e15fb6ef4876094 to your computer and use it in GitHub Desktop.
A strongly typed useReducer hook allowing you to use setState as used in react classed based components
/**
* Mimic set state function of react
* @param prevState
* @param property
*/
type TypedReducer<T> = (
prevState: T,
property: { [K in keyof T]?: T[K] }
) => T;
/**
* Declare State
*/
type State = { //...state properties }
/**
* Usage
*/
const reducer: TypedReducer<State> = (prevState, property) => ({
...prevState,
...property
});
// within your component
const initState: State = { // ...initial state properties }
const [state, setState] = useReducer(reducer, initState);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment