ReactJS Design Pattern ~State Machine Pattern~
Source: Dev.to
Overview
The State Machine Pattern helps keep a React codebase readable, maintainable, and productive. Instead of juggling multiple boolean state variables, a single status variable can represent the component’s state, simplifying state management and preventing impossible combinations (e.g., being both loading and in an error state simultaneously).
Before
function App() {
const [error, setError] = useState(true);
const [loading, setLoading] = useState(false);
const [ready, setReady] = useState(false);
const handleNextState = () => {
if (status === "ready") {
setLoading(true);
setReady(false);
setError(false);
} else if (status === "loading") {
setError(true);
setReady(false);
setLoading(false);
} else if (status === "error") {
setReady(true);
setError(false);
setLoading(false);
}
};
return (
## State Machine Pattern
Next State
{loading &&
Loading...
}
{error &&
Something went wrong!
}
{ready &&
Ready to go!
}
);
}
State Machine Pattern
Next State
{loading &&
Loading...
}
{error &&
Something went wrong!
}
{ready &&
Ready to go!
}
After
function App() {
const [status, setStatus] = useState('ready');
const handleNextState = () => {
if (status === "ready") {
setStatus("loading");
} else if (status === "loading") {
setStatus("error");
} else if (status === "error") {
setStatus("ready");
}
};
return (
## State Machine Pattern
Next State
{status === "loading" &&
Loading...
}
{status === "error" &&
Something went wrong!
}
{status === "ready" &&
Ready to go!
}
);
}