Last active
January 26, 2020 19:19
-
-
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
This file contains hidden or 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
/** | |
* 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