JavaScript and React course Β· Module 15: Patterns and Architecture

Advanced Patterns - State Machines and Provider Pattern

9 min read Β·
In this lesson8

The theme switch sits in the header, yet every panel of the station needs to know the colors. The launch procedure has seven stages and several boolean flags that can contradict each other. Now that you know the basic React patterns, it is time for advanced techniques that solve both problems: the Provider Pattern for sharing state and state machines for keeping complex processes under control. In the space station, it is like installing advanced control systems.

Provider Pattern - Central distribution system

The Provider Pattern is an extension of the Context API. We create a dedicated provider that encapsulates both state and logic, and exposes only a ready-made object to components:

const ThemeContext = createContext();

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('dark');

  const toggleTheme = useCallback(() => {
    setTheme(prev => prev === 'dark' ? 'light' : 'dark');
  }, []);

  const value = useMemo(() => ({
    theme, toggleTheme
  }), [theme, toggleTheme]);

  return (
    <ThemeContext.Provider value={value}>
      <div className={`app-${theme}`}>
        {children}
      </div>
    </ThemeContext.Provider>
  );
}

useCallback keeps the same toggleTheme function between renders, and useMemo creates the value object anew only when the theme changes, so consumers do not re-render needlessly. The second half of the pattern is the hook through which components read the context:

// Custom hook for consumption
function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}

createContext() without a default value gives undefined outside the provider, so the hook throws a readable error instead of letting a component run on empty data. The recipe is always the same: a context, a provider with state and logic, a hook for consumption, wrapping the application in the provider and using the hook in components. In React 19 you can also read a context with the use function, and <ThemeContext> itself can act as the provider.

The same recipe gives you the station's notification center. The provider holds a notifications array and three functions that never change the old array, they create a new one instead:

const NotificationContext = createContext(null);
let nextId = 0;

function NotificationProvider({ children }) {
  const [notifications, setNotifications] = useState([]);

  const addNotification = useCallback((message, type = 'info') => {
    const id = ++nextId;
    setNotifications(prev => [...prev, { id, message, type }]);
  }, []);

  const removeNotification = useCallback((id) => {
    setNotifications(prev => prev.filter(n => n.id !== id));
  }, []);

  const clearAll = useCallback(() => setNotifications([]), []);

  const value = useMemo(
    () => ({ notifications, addNotification, removeNotification, clearAll }),
    [notifications, addNotification, removeNotification, clearAll]
  );

  return (
    <NotificationContext.Provider value={value}>
      {children}
    </NotificationContext.Provider>
  );
}

addNotification appends a new entry with a unique id from the counter, removeNotification uses filter to keep every entry except one, and clearAll puts an empty array in place. The functions wrapped in useCallback do not change, so value is created anew only when the list changes. You write the useNotifications hook just like useTheme, with a readable error outside the provider.

Provider composition

When we have many providers, the tree starts to look like a pyramid, and composition becomes key. Plain nesting looks like this:

// Instead of nesting:
function App() {
  return (
    <ThemeProvider>
      <AuthProvider>
        <NotificationProvider>
          <AppContent />
        </NotificationProvider>
      </AuthProvider>
    </ThemeProvider>
  );
}

The ComposeProviders component builds the same pyramid from an array. reduceRight starts from the last provider, so the first one in the array ends up on the outside, just like in the nested version:

// We can use the compose pattern:
function ComposeProviders({ providers, children }) {
  return providers.reduceRight(
    (acc, Provider) => <Provider>{acc}</Provider>,
    children
  );
}

function App() {
  return (
    <ComposeProviders
      providers={[ThemeProvider, AuthProvider, NotificationProvider]}
    >
      <AppContent />
    </ComposeProviders>
  );
}

The resulting tree is identical, only the notation changed. This trick cannot pass props to specific providers, though, so with three providers I would stick to nesting and keep ComposeProviders for long lists.

State Machines - Controlled state transitions

A state machine eliminates "impossible states" and guarantees that the application is always in one of the defined states. We start with a map: for every state we list the events and the state each one leads to:

// States and transitions for the launch process
const launchMachine = {
  idle: {
    START_PREFLIGHT: 'preflight'
  },
  preflight: {
    CHECKS_PASSED: 'countdown',
    CHECKS_FAILED: 'error'
  },
  countdown: {
    COUNTDOWN_DONE: 'launching',
    ABORT: 'aborted'
  },
  launching: {
    LAUNCH_SUCCESS: 'inFlight',
    LAUNCH_FAILURE: 'error'
  },
  inFlight: {},
  error: {
    RETRY: 'idle'
  },
  aborted: {
    RETRY: 'idle'
  }
};

We read idle: { START_PREFLIGHT: 'preflight' } like this: in the idle state, the START_PREFLIGHT event takes us to preflight. The inFlight state has no transitions, so it is a final state. Now the hook that guards this map:

function useMachine(machine, initialState) {
  const [state, setState] = useState(initialState);

  const send = useCallback((event) => {
    setState(current => {
      const nextState = machine[current]?.[event];
      if (!nextState) {
        console.warn(`No transition for ${event} in state ${current}`);
        return current;
      }
      return nextState;
    });
  }, [machine]);

  return [state, send];
}

send looks up the transition in the map, and for an unknown event it stays in the current state and prints a warning in the console. The component only sends events and shows the buttons that match the state:

// Usage
function LaunchControl() {
  const [state, send] = useMachine(launchMachine, 'idle');

  return (
    <div className="launch-control">
      <h2>State: {state}</h2>
      {state === 'idle' && (
        <button onClick={() => send('START_PREFLIGHT')}>
          Start Preflight
        </button>
      )}
      {state === 'preflight' && (
        <>
          <button onClick={() => send('CHECKS_PASSED')}>
            Checks Passed
          </button>
          <button onClick={() => send('CHECKS_FAILED')}>
            Checks Failed
          </button>
        </>
      )}
      {state === 'countdown' && (
        <button onClick={() => send('ABORT')}>ABORT</button>
      )}
      {state === 'error' && (
        <button onClick={() => send('RETRY')}>Retry</button>
      )}
    </div>
  );
}

Even if some button sent a wrong event, the state would not change, because the map does not allow it. Notice, however, that after ABORT the component shows no RETRY button, even though the map allows it. Such oversights disappear when you generate the buttons from the machine itself:

function useMachine(machine, initialState) {
  // ... state and send as above
  const canSend = (event) => Boolean(machine[state]?.[event]);
  const events = Object.keys(machine[state] ?? {});
  return { state, send, canSend, events };
}

function MachineButtons({ events, send }) {
  return events.map(event => (
    <button key={event} onClick={() => send(event)}>{event}</button>
  ));
}

The hook now returns an object instead of an array, because there are more values. canSend will come in handy for graying out buttons, and the events list always matches the map.

Why is a State Machine better than booleans?

Consider a typical scenario without a state machine, familiar from forms and loading screens. We have a component with several boolean states:

// WITHOUT state machine - "impossible states" are possible
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);

// What if isLoading and isError are BOTH true at the same time?
// That's an "impossible state", but nothing prevents it!

Three flags give eight combinations, and only four of them make sense. With a state machine this problem disappears: the component is ALWAYS in exactly one state and cannot be in the loading and error states at the same time. It is like the safety systems of a ship: you cannot be in flight mode and docking mode at once. For elaborate processes, reach for the XState library, which adds nested states, among other things.

Reminder: useLocalStorage

ThemeProvider has one flaw: after a page refresh the theme goes back to dark. A custom hook that works like useState but saves the value in the browser will help:

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const saved = localStorage.getItem(key);
    return saved !== null ? JSON.parse(saved) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

The function passed to useState is an initializer: React calls it only on the first render. In the provider, it is enough to replace one line with useLocalStorage('space-theme', 'dark'), and the rest of the code does not change. Just remember that localStorage does not exist on the server, for example in Next.js.

When to use specific patterns?

SituationPattern
Sharing data in the treeProvider Pattern
Multi-step processesState Machines
Form with validationuseForm hook + State Machine
List with filteringCustom hook + Presentational
Component with variantsComposition + Props
Interchangeable behaviors, e.g. the sorting methodStrategy: a function in a prop
Pub/sub communicationObserver: EventBus
Complex configuration assembled step by stepBuilder
Abstraction of data accessRepository: a module that hides fetch

Strategy, Observer and Builder are classic patterns from the 1994 book "Design Patterns", and you will find Repository in Martin Fowler's catalog of application architecture patterns. Each one answers a different need: composition builds the structure, Observer handles communication, Strategy swaps behaviors, Builder assembles a complex configuration, and Repository hides data access.

How to choose a pattern?

These patterns cannot honestly be ranked from the simplest to the hardest, because each one solves a different problem: Observer is not a "higher level" of Strategy. Instead of a ranking, follow a procedure, the way a pilot follows a checklist before launch:

  1. Name the problem. What repeats, what is hard to change, who needs to find out about a change?
  2. Check whether props and children are enough. Plain composition solves a surprising amount.
  3. Pick the simplest pattern that solves exactly this problem. The table above suggests candidates.
  4. Introduce it in one place and check whether the code really got simpler.
  5. Only then extend it to the rest of the application.

If the code did not get simpler in the fourth step, roll the change back. A pattern that does not solve the named problem is just one more layer to understand.

Summary

The Provider Pattern and State Machines are advanced tools that solve real problems in large React applications. The Provider centralizes data and logic, eliminating "prop drilling". The State Machine organizes complex state flows and guarantees that the application never ends up in an undefined state. Both patterns can be combined: a Provider can expose a state machine to the whole tree, giving every view access to the mission state and the transition functions. My advice: when you catch yourself adding a third isSomething flag, draw a state map. In the final project you will combine all the patterns from this module.

Remember: a good station has one power source and clearly described operating modes.

Code for this lesson: App.jsx
import React, { createContext, useContext, useState, useCallback, useMemo } from 'react';

// =============================================
// PROVIDER PATTERN
// =============================================
const ThemeContext = createContext();

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('dark');
  const toggleTheme = useCallback(() => setTheme(t => t === 'dark' ? 'light' : 'dark'), []);
  const value = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme]);

  return (
    <ThemeContext.Provider value={value}>
      <div className={`theme-${theme}`}>{children}</div>
    </ThemeContext.Provider>
  );
}

function useTheme() {
  const ctx = useContext(ThemeContext);
  if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
  return ctx;
}

// =============================================
// STATE MACHINE
// =============================================
const launchMachine = {
  idle:       { START_PREFLIGHT: 'preflight' },
  preflight:  { CHECKS_PASSED: 'countdown', CHECKS_FAILED: 'error' },
  countdown:  { COUNTDOWN_DONE: 'launching', ABORT: 'aborted' },
  launching:  { LAUNCH_SUCCESS: 'inFlight', LAUNCH_FAILURE: 'error' },
  inFlight:   {},
  error:      { RETRY: 'idle' },
  aborted:    { RETRY: 'idle' },
};

// The current state is the last history entry: one value in state and a pure updater function
function useMachine(machine, initialState) {
  const [history, setHistory] = useState([initialState]);
  const state = history[history.length - 1];

  const send = useCallback((event) => {
    setHistory(h => {
      const next = machine[h[h.length - 1]]?.[event];
      return next ? [...h, next] : h;
    });
  }, [machine]);

  // Buttons are generated from the available events, as the lesson recommends
  const events = Object.keys(machine[state] ?? {});
  return { state, send, events, history };
}

// =============================================
// COMPOSE PROVIDERS
// =============================================
function ComposeProviders({ providers, children }) {
  return providers.reduceRight(
    (acc, Provider) => <Provider>{acc}</Provider>,
    children
  );
}

// =============================================
// COMPONENTS
// =============================================
const themeLabels = { dark: 'dark', light: 'light' };

function ThemeToggle() {
  const { theme, toggleTheme } = useTheme();
  return (
    <button className="theme-toggle" onClick={toggleTheme}>
      Theme: {themeLabels[theme]}
    </button>
  );
}

const stateColors = {
  idle: '#999', preflight: '#ff9800', countdown: '#ff5722',
  launching: '#f44336', inFlight: '#4caf50', error: '#f44336', aborted: '#9e9e9e',
};

const stateLabels = {
  idle: 'Ready', preflight: 'Preflight Checks', countdown: 'Countdown',
  launching: 'Launching...', inFlight: 'In Flight!', error: 'Error', aborted: 'Aborted',
};

// Button labels and colors for every machine event
const eventButtons = {
  START_PREFLIGHT: { label: 'Start Preflight', color: 'primary' },
  CHECKS_PASSED: { label: 'Checks Passed', color: 'success' },
  CHECKS_FAILED: { label: 'Checks Failed', color: 'danger' },
  COUNTDOWN_DONE: { label: 'Go!', color: 'success' },
  ABORT: { label: 'ABORT', color: 'danger' },
  LAUNCH_SUCCESS: { label: 'Success', color: 'success' },
  LAUNCH_FAILURE: { label: 'Failure', color: 'danger' },
  RETRY: { label: 'Retry', color: 'primary' },
};

function LaunchControl() {
  const { state, send, events, history } = useMachine(launchMachine, 'idle');

  return (
    <div className="launch-control">
      <h3>State Machine: Launch Sequence</h3>
      <div className="state-display" style={{ borderColor: stateColors[state] }}>
        <span className="state-label" style={{ color: stateColors[state] }}>
          {stateLabels[state]}
        </span>
        <code className="state-id">{state}</code>
      </div>
      <div className="action-btns">
        {events.map(event => (
          <button key={event} className={`btn btn-${eventButtons[event].color}`} onClick={() => send(event)}>
            {eventButtons[event].label}
          </button>
        ))}
        {events.length === 0 && <p className="final-note">Final state: the machine has no more transitions.</p>}
      </div>
      <div className="history">
        <h4>State History</h4>
        <div className="history-flow">
          {history.map((s, i) => (
            <span key={i} className="history-item" style={{ color: stateColors[s] }}>
              {stateLabels[s]}{i < history.length - 1 && ' β†’ '}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

// =============================================
// MAIN APP
// =============================================
function AppContent() {
  return (
    <div className="app">
      <div className="top-bar">
        <h1>Advanced Patterns</h1>
        <ThemeToggle />
      </div>
      <p className="subtitle">Provider Pattern + State Machines</p>
      <LaunchControl />
    </div>
  );
}

export default function App() {
  // With one provider a plain <ThemeProvider> would do; here you see the ComposeProviders mechanism itself
  return (
    <ComposeProviders providers={[ThemeProvider]}>
      <AppContent />
    </ComposeProviders>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Why should a custom hook using context (e.g., useTheme) check whether it is used inside a provider?

  2. 2. What is the main advantage of using a state machine instead of multiple boolean variables?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Finish the notification centre built on the Provider Pattern. ___BLANK1___: addNotification returns a new array with the existing notifications and the new object { id, message, type } at the end. ___BLANK2___: removeNotification keeps every notification except the one with the given id. ___BLANK3___: clearAll sets an empty list. ___BLANK4___: useNotifications throws an error when it is used outside NotificationProvider (useContext then returns undefined).

  • Vertical ordering

    Arrange the Provider Pattern implementation steps in the correct order:

  • Code editor

    Finish the state machine of the docking process. ___BLANK1___: after the UNDOCK event the ship goes back to the approaching state. ___BLANK2___: send returns the next state from the map, machine[current]?.[event], and when the current state has no transition for this event, it stays in current. ___BLANK3___: canSend(event) returns true or false depending on whether the transition exists in the current state. ___BLANK4___: events are the event names of the transition object of the current state (for a state missing from the map, an empty object, so an empty list). DockingControl creates buttons from events.

  • Click in order

    Arrange the transition definition: in the idle state the START event moves the machine to the running state.

  • Vertical ordering

    Arrange the syntax for using ComposeProviders:

  • Code editor

    Create a useLocalStorage(key, initialValue) hook that works like useState but remembers the value in localStorage. ___BLANK1___: when there is a saved entry under the key, the initializer returns it converted from JSON back into a value (a number comes back as a number). ___BLANK2___: the effect saves the current value converted to JSON under the key. ___BLANK3___: the effect runs again after the key or the value changes. The Settings component uses the hook for the theme, the language and the text size.

  • Vertical ordering

    Arrange the steps of choosing a React pattern in the order you take them:

  • Horizontal ordering

    Arrange the syntax for rendering a polymorphic component with the as prop:

  • Click in order

    Click in order the stages a flag change goes through in an app with FeatureFlagProvider:

  • Vertical ordering

    Arrange the stages of a listener's lifecycle in the useEventListener hook:

  • Vertical ordering

    Arrange the syntax for using the declarative Feature component:

  • Click in order

    Click the elements that form an event emission in EventBus:

  • Vertical ordering

    Arrange the layers of the Container/Presentational pattern from lowest:

  • Horizontal ordering

    Arrange the syntax for rendering a SpaceCard component with slots:

  • Vertical ordering

    Arrange the steps for refactoring a monolithic component to Atomic Design:

  1. Coding taskPractice: Provider Pattern
  2. QuestionProvider Pattern - Validation
  3. Put in orderProvider Pattern Implementation Steps
  4. Coding taskPractice: Docking State Machine
  5. Click in orderState Machine Transitions
  6. Put in orderComposeProviders Syntax
  7. QuestionState Machine Advantages
  8. Coding taskPractice: useLocalStorage
  9. Put in orderReact Pattern Selection Process
  10. Put in orderPolymorphic Component as Syntax
  11. Click in orderThe Path of a Flag from State to Screen
  12. Put in orderEventBus Listener Lifecycle
  13. Put in orderDeclarative Feature Component Syntax
  14. Click in orderEmitting an Event in EventBus
  15. Put in orderContainer/Presentational Structure
  16. Put in orderSlot Pattern Syntax in SpaceCard
  17. QuestionChoosing a Communication Pattern
  18. Put in orderRefactoring to Atomic Design Process
  19. QuestionReact Patterns Summary

Useful articles