Encapsulate as much state as possible
blacksheepcode.com·4h·
Discuss: r/reactjs
Flag this post

Published: October 31, 2025

Let’s say we have a nice simple component like this:

☝️ Interactive demo

Click the button to see it transition from pending to loading to success.

You click the button, it transitions to a loading state, then it transitions to either a success or error state.

What I commonly see, is the component will be implemented with a interface like this:

4type SpecialButtonProps = {
5    onClick: () => void;
6    state: "loading" | "error" | "success" | "pending";
7};

Implementation

9export function SpecialButton(props: SpecialButtonProps) {
10    return <button onClick={props.onClick} disabled={props.state === "loading"} className={`special-button ${props.state}`}>
11        {props.state === "loading" && <span>Loading...</span>}
12        {props.s...

Similar Posts

Loading similar posts...