Skip to content

Instantly share code, notes, and snippets.

Last active May 26, 2020
What would you like to do?
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];

This comment has been minimized.

Copy link
Owner Author

@mrcoles 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