React Advanced

Finite State Machines

Modeling UI states, state charts, guards, and complex state transitions.

Advertisement

Finite State States

Modeling UI states, state charts, guards, and complex state transitions.

Overview

FSMs eliminate impossible states and make complex UI logic predictable.

Key Concepts

  • States — Finite set of possible states
  • Events — Trigger transitions between states
  • Guards — Conditions for valid transitions
  • Actions — Side effects during transitions
  • Hierarchical States — Nested states for complex logic

Code Examples

// Simple FSM without library
function useFSM(initialState, transitions) {
  const [state, setState] = useState(initialState);

  const send = useCallback((event) => {
    setState(currentState => {
      const transition = transitions[currentState]?.[event];
      if (transition) {
        if (typeof transition === 'function') return transition();
        return transition;
      }
      return currentState;
    });
  }, [transitions]);

  return [state, send];
}

// Usage
const machine = {
  idle: { START: 'loading', RESET: 'idle' },
  loading: { SUCCESS: 'success', FAILURE: 'failure' },
  success: { RESET: 'idle' },
  failure: { RETRY: 'loading', RESET: 'idle' }
};

function DataLoader() {
  const [state, send] = useFSM('idle', machine);

  return (
    <div>
      {state === 'idle' && <button onClick={() => send('START')}>Load</button>}
      {state === 'loading' && <p>Loading...</p>}
      {state === 'success' && <p>Data loaded!</p>}
      {state === 'failure' && (
        <button onClick={() => send('RETRY')}>Retry</button>
      )}
    </div>
  );
}

Practice

Model a multi-step checkout process with FSM including validation and error recovery.