Skip to content

Instantly share code, notes, and snippets.

@andreievg
Last active July 18, 2023 11:46
Show Gist options
  • Save andreievg/f1bef9429eb5101cbbc016c4df9936b9 to your computer and use it in GitHub Desktop.
Save andreievg/f1bef9429eb5101cbbc016c4df9936b9 to your computer and use it in GitHub Desktop.
Use state wrapper to expose partial state setter
export const usePartialState = <T extends object>(
initial: T
): {
state: T;
setState: Dispatch<SetStateAction<T>>;
setPartialState: (newPartialState: Partial<T>) => void;
} => {
const [state, setState] = useState<T>(initial);
return {
state,
setState,
setPartialState: newPartialState =>
setState(state => ({ ...state, ...newPartialState })),
};
};
@andreievg
Copy link
Author

Simplifiest partial state update

const { state, setState, setPartialState } = usePartialState({one: true, two: 2});

// ...

setState(state => ({ ...state, two: 2 }));
// vs
setPartialState({two: 2});

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