# State

> Replace state-based if/switch spaghetti with separate State classes — the object delegates its behavior to whichever State is currently active.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/state/

---

## Description
**Intent**: Eliminate giant conditionals by encapsulating state-specific behavior into dedicated State objects.

**Context**: Your object behaves differently depending on internal state — a vending machine that's idle vs. dispensing vs. out of stock, a traffic light cycling through phases, a game character with different ability sets. The code is a wall of if-else or switch statements that grows every time a new state is added.

**Solution**: Define a State interface with methods for all state-specific behaviors. Create a concrete class for each state. The Context object holds a reference to the current State and delegates method calls to it. State transitions happen by swapping the reference.


## Use Cases
Use when an object's behavior changes significantly based on internal state, the state count is large or growing, and state-specific logic keeps creeping into the main class.



## Implementation Example

```javascript
class State {
  handle(context) {}
}

class ConcreteStateA extends State {
  handle(context) {
    console.log("State A handling context. Transitioning to B.");
    context.transitionTo(new ConcreteStateB());
  }
}

class ConcreteStateB extends State {
  handle(context) {
    console.log("State B handling context. Transitioning to A.");
    context.transitionTo(new ConcreteStateA());
  }
}

```



## Trade-offs


### Advantages

- Each state's logic lives in its own class — no more 500-line switch statements.

- Add new states without touching existing state classes.




### Considerations & Drawbacks

- Complete overkill for simple two-state or rarely-changing state machines.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/state)

