Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Last active March 4, 2021 04:31
Show Gist options
  • Save gaurangrshah/83455a902be48e4e9edf9a804f739b13 to your computer and use it in GitHub Desktop.
Save gaurangrshah/83455a902be48e4e9edf9a804f739b13 to your computer and use it in GitHub Desktop.
@react #useStates #simple-state-machine
import { useEffect, useState } from "react";
export function useStates(defaultState) {
const [states, setStates] = useState({});
//SCOPE: used as a make-shift logger, triggers on each state change
useEffect(() => console.log("states monitor", states), [states]);
useEffect(() => {
// SCOPE: set initial state - or - throw if no defaultState
if (!defaultState) {
throw new Error(
"useStates(): Error: must provide default state to initialize hook"
);
}
setStates(defaultState);
}, []);
const setters =
Object.keys(states)?.length &&
Object.keys(states)
?.map((state) => ({
// SCOPE: create an array of setState function objects for each key in current state
[`set${state[0].toUpperCase() + state.substring(1)}`]: (newState) => {
setStates((prevState) => ({ ...prevState, [state]: newState }));
},
}))
// SCOPE: reduce the array of setState functions objects into a single object
.reduce((obj, acc) => ({ ...acc, ...obj }), {});
return { ...states, ...setters };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment