Last active
May 26, 2020 15:19
-
-
Save mrcoles/dcbe2117ba655127a2685db50c43a259 to your computer and use it in GitHub Desktop.
Helpful React hooks (for now just one…)
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
| import { useState, Dispatch, SetStateAction } from 'react'; | |
| export const useUpdateState = <S extends object>( | |
| defaultState: S | |
| ): [S, (newState: Partial<S>) => void, Dispatch<SetStateAction<S>>] => { | |
| const [state, setState] = useState(defaultState); | |
| const updateState = (newState: Partial<S>) => | |
| setState((prevState) => ({ ...prevState, ...newState })); | |
| return [state, updateState, setState]; | |
| }; | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
useUpdateStatefunctions just likeuseState, however theupdateStatefunction that it returns accepts a partial of the state and applies those changes to the state object. This functions much like the old class-based componentthis.setStatemethod, e.g.,In order to avoid confusion, you might want to rename "setState" to "putState" in your code, so it’s clear that one replaces and one updates, e.g.,
const [ state, updateState, putState ] = …