・The State Machine Pattern is helpful for keeping codebase readable, maintainable, and productive. This pattern replaces multiple boolean state variables with a single status variable that can have different values. This simplifies state management and prevents impossible states like being both loading and having an error at the same time.
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 (
<div>
<h1>State Machine Pattern</h1>
<button onClick={handleNextState}>Next State</button>
{loading && <p>Loading...</p>}
{error && <p>Something went wrong!</p>}
{ready && <p>Ready to go!</p>}
</div>
);
}
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 (
<div>
<h1>State Machine Pattern</h1>
<button onClick={handleNextState}>Next State</button>
{status === "loading" && <p>Loading...</p>}
{status === "error" && <p>Something went wrong!</p>}
{status === "ready" && <p>Ready to go!</p>}
</div>
);
}
Top comments (0)