ReactJS Design Pattern ~State Machine Pattern~

Published: (January 5, 2026 at 07:01 PM EST)
2 min read
Source: Dev.to

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!
}
    
  );
}
Back to Blog

Related posts

Read more »