Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Last active May 26, 2020 15: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 mrcoles/dcbe2117ba655127a2685db50c43a259 to your computer and use it in GitHub Desktop.
Save mrcoles/dcbe2117ba655127a2685db50c43a259 to your computer and use it in GitHub Desktop.
Helpful React hooks (for now just one…)
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];
};
@mrcoles
Copy link
Author

mrcoles commented May 24, 2020

useUpdateState functions just like useState, however the updateState function 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 component this.setState method, e.g.,

type MyState = { isComplete: boolean; hasErrors: boolean; }

const [ state, updateState, setState ] = useUpdateState<MyState>({ isComplete: false, hasErrors: false });

updateState({ isComplete: true }); // leads to a new state of `{ isComplete: true, hasErrors: false }`

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 ] = …

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment