Skip to content

    Frontend System Design

    Local vs Global State in the Front End

    Decide where front-end state lives: in a component, a lifted parent, context or a module-level store. Learn placement rules, lifetimes and costs, with a lab.

    By Published 19 min read

    Share

    Flagship lessonbeginnerReact labFrontend System Design

    Before this: Component-Based Architecture

    What you'll learn: By the end of this lesson you will be able to describe state by its owner, scope and lifetime, decide whether a piece of state belongs in one component, a common parent, a context provider or a module-level store, keep state minimal so it cannot go stale or contradict itself, use composition to avoid prop drilling, explain what a global store costs (reach, lifetime, tests, server rendering), and run a small lab that shows each rule on a product page.

    Think of a restaurant kitchen. Each cook keeps a private notepad for the order they are cooking right now. When two cooks need the same fact, such as "table 7 is allergic to nuts", one of them tells the other, or it goes on a ticket both can read. A whiteboard on the wall is for facts the whole kitchen needs. Now imagine every note, including "I am stirring", goes on the wall whiteboard. It fills up, nobody knows who may erase what, and when one cook changes a line the whole kitchen looks up.

    Front-end state has the same shape. Some facts matter to one component and should stay private. Some must be shared by two neighbours. A few really are for the whole page. The craft is putting each fact in the smallest place that works, and moving it only when a real need appears.

    The running example is a product page. A search box filters a list of products. Clicking a product selects it. Every product has an Add button, and a cart badge in the page header shows how many items are in the cart. A tabbed panel holds a note the shopper types. The names and prices in the lab are made up.

    The core idea

    Three statements carry the lesson.

    1. State has an owner, a scope and a lifetime. The owner is the component, provider or module that holds it. The scope is who can read and change it. The lifetime is how long it survives. These three facts are the whole difference between "local" and "global".
    2. Keep state as low as possible and as high as necessary. React's documentation describes the move: remove state from the children, move it to their closest common parent, and pass it down. Anything higher than that is a choice with a price.
    3. Climb one rung at a time. Local state, then lifted state, then composition, then context with a reducer, then a module-level store or a state library. Each rung adds reach and costs something (readers you cannot see, a longer lifetime, harder tests).

    Three illustrations run through the lesson: a minimal example (the search box and the list), a realistic example (the whole product page with a cart), and a failure example (a global store that leaks, on the server and between tests).

    What counts as state

    State is data that changes over time and that the screen must react to. React's guide "Thinking in React" gives three questions for any piece of data. Does it remain unchanged over time? Then it is not state. Is it passed in from a parent through props? Then it is not state. Can you compute it from existing state or props? Then it is definitely not state. Its principle is to keep state DRY: find the minimal representation and compute everything else on demand.

    For the product page, the search text and the selected product's id are state. The list of visible products is not: it is a function of the products and the search text. The cart is state, but a cart total is not.

    Four ways to get state wrong before placement even matters

    React's "Choosing the State Structure" page lists principles that apply to local and global state alike. The lab shows four of them as pairs: the version that breaks and the version that follows the rule.

    Mistake What goes wrong The rule
    Redundant state: storing a list that render could compute The stored copy only changes where you remember to update it "If you can calculate some information from the component's props or its existing state variables during rendering, you should not put that information into that component's state."
    Duplicated state: storing the selected object next to the list it came from A rename or delete leaves the copy stale "For UI patterns like selection, keep ID or index in state instead of the object itself."
    Contradictory state: two booleans such as isSending and isSent Forgetting one set call leaves both true Replace them with one status variable with three valid values
    Nested state: deeply hierarchical objects Updates need long spreads and are easy to get wrong Prefer a flat structure

    Local state: owner and lifetime

    A component can remember things with useState. React's guide explains why a plain variable is not enough: local variables do not persist between renders, and changing them does not trigger a render. State retains the data and triggers the render. It is also private: if you render the same component twice, each copy has completely isolated state, and a parent cannot change it.

    Local state also has a lifetime. React keeps a component's state for as long as the component is rendered at its position in the tree. If it is removed, or a different component appears in the same position, React discards the state. A key makes React treat a component as a new one, which resets its state on purpose.

    Figure 1. The note disappears when its tab unmounts

    sequenceDiagram accTitle: Local state is destroyed when its component unmounts accDescr: A shopper types a note in a note component that holds its own state. Switching to another tab removes the note component, so React destroys its state. Switching back creates a new note component with an empty draft. If the draft lives in the parent, the parent stays mounted and the text is still there. participant S as Shopper participant P as Page (parent) participant N as Note component S->>N: types "buy oat milk" Note over N: draft lives in N S->>P: clicks "Show other" P->>N: unmount Note over N: state destroyed S->>P: clicks "Show note" P->>N: mount a new Note Note over N: draft is empty Note over P: if the draft lived here, it would still be "buy oat milk"

    How to read this: the same user actions run against two designs. With the draft in the note, it dies with the note. With the draft in the parent, it lives as long as the parent does. The lab has one test for each.

    This is the first lesson about lifetime: a state's lifetime is its owner's lifetime. If a draft must survive a tab switch, an owner that outlives the tab must hold it. If it must survive a page reload, no component can hold it. That is the topic of persistence, covered in the lesson on state persistence and synchronization.

    Lifting state up

    When a second component needs the same state, React's guide gives three steps: remove the state from the children, pass hard-coded data from the common parent, then add state to the parent and pass it down along with event handlers. The result follows the idea of a single source of truth. The guide is careful about what that means: not that all state lives in one place, but that each piece of state has one specific component that holds it.

    A component driven by props is called controlled, and one with its own local state uncontrolled; the guide notes these are not strict terms.

    The lab's minimal example is a search box and a list. With the query inside the box, the box works but the list never hears about it. After lifting, the closest common parent owns the query:

    export function LiftedCatalogue({ products }: { products: readonly Product[] }) {
      const [query, setQuery] = useState("");
      return (
        <>
          <SearchBox value={query} onChange={setQuery} />
          <ProductList products={matches(products, query)} />
        </>
      );
    }

    Notice that matches(products, query) is computed in render, not stored. The parent owns one piece of state (query), and everything else is derived.

    Prop drilling and composition

    Lifting has a cost when the common parent is far away. React's guide on context calls the result prop drilling: passing a prop deeply through components that do not use it. It recommends two things to try before context. First, start by passing props, because that makes it clear which components use which data. Second, extract components and pass JSX as children, which reduces the number of layers between the component that specifies the data and the one that needs it.

    Figure 2. Drilled versus composed

    flowchart LR accTitle: Prop drilling compared with composition accDescr: In the drilled version a page passes a userName prop to a shell, which passes it to a sidebar, which passes it to a greeting that uses it. In the composed version the page builds the greeting element itself and passes it down as children, so the shell and sidebar receive only children. subgraph Drilled D1["Page
    userName"] --> D2["Shell
    userName (unused)"] --> D3["Sidebar
    userName (unused)"] --> D4["Greeting
    uses userName"] end subgraph Composed C1["Page
    builds Greeting"] --> C2["Shell
    children"] --> C3["Sidebar
    children"] --> C4["Greeting
    already has userName"] end

    How to read this: in the left column two components carry data they never use. In the right column the page creates the element that needs the data and hands it down, so the middle components know only about children. The lab records the props each middle component receives and asserts exactly that.

    Composition is the cheapest way to shorten the distance between an owner and a reader, because it adds no new mechanism. It is also why a deep tree does not by itself justify global state.

    Context with a reducer: shared inside a subtree

    When many distant components need to read and change the same state, React's guide on scaling up combines a reducer with context: create the context, put state and dispatch into it, and use it anywhere in the tree. A reducer is a function that takes the current state and an action and returns the next state. React's documentation requires reducers to be pure: the same inputs always give the same output, with no requests, timeouts or other side effects. Purity makes them easy to test on their own.

    The lab's cart is one such reducer. Its state is a map from product id to quantity:

    export function cartReducer(state: CartState, action: CartAction): CartState {
      switch (action.type) {
        case "add":
          return { lines: { ...state.lines, [action.id]: (state.lines[action.id] ?? 0) + 1 } };
        case "remove": {
          const { [action.id]: _removed, ...rest } = state.lines;
          return { lines: rest };
        }
        case "clear":
          return emptyCart;
      }
    }

    The provider holds useReducer and puts state and dispatch into two contexts. React's guide does the same, and wraps each context in a custom Hook, which "lets you later split these contexts further or add some logic to these functions". A badge in the header and an Add button deep in the list now share the cart with nothing between them.

    Two properties follow from where the state lives:

    • The scope is the provider's subtree. The nearest provider above a component supplies its value. Two providers are two separate carts, and a component outside any provider has none (the lab's hook throws a clear error).
    • The lifetime is the provider's lifetime. When the provider unmounts, its state is gone, and a new provider starts empty. The lab has a test for that.

    Context has a rendering cost. React re-renders all components that read a context when the provider receives a different value, compared with Object.is, and memo does not stop it. The lesson on React context and render cost covers this in detail: Context and Its Render Cost in React. Placement affects cost: a context holding a rarely changing value (the signed-in user) is cheap; one holding a value that changes on every keystroke is not.

    A module-level store: global in the true sense

    Sometimes state must be reachable from places a provider cannot reach, or must outlive the whole component tree. A module-level store is a plain object created when a JavaScript module loads. Everything that imports the module gets the same instance. The lab's store is 20 lines:

    export function createStore<S>(initial: S): Store<S> {
      let state = initial;
      const listeners = new Set<() => void>();
      return {
        getState: () => state,
        setState(update) {
          const next = update(state);
          if (Object.is(next, state)) return;
          state = next;
          for (const listener of listeners) listener();
        },
        subscribe(listener) {
          listeners.add(listener);
          return () => {
            listeners.delete(listener);
          };
        },
      };
    }

    React connects to such a store with useSyncExternalStore, a hook that subscribes a component to an external store. It takes a subscribe function (which should return a cleanup function) and a getSnapshot function. While the store has not changed, repeated calls to getSnapshot must return the same value, and React re-renders when the returned value differs, compared with Object.is. React also states that the snapshot must be immutable: if the underlying data is mutable, return a new snapshot on change and otherwise the cached one.

    export function GlobalCartBadge() {
      renderLog.record("GlobalCartBadge");
      const count = useSyncExternalStore(globalCart.subscribe, () => cartCount(globalCart.getState()));
      return <p role="status">Cart: {count}</p>;
    }

    The badge subscribes to the count, so it re-renders when the count changes. The Add button only calls dispatchGlobal and never subscribes, so it does not re-render. The lab counts both: the badge renders three times for two additions (the first render plus two changes) and the button once.

    Figure 3. A global store, its subscribers and its callers

    A module-level store notifies subscribers; callers that only dispatch are never notifiedAdd button to Module store (setState); Module store to Cart badge (notify); Module store to Other readers (notify)MODULE SCOPE (LIVES AS LONG AS THE PAGE'S JAVASCRIPT)Add button: dispatches onlyAdd buttondispatches onlyModule store: one per page loadModule storeone per page loadCart badge: subscribedCart badgesubscribedOther readers: any root, any depthOther readersany root, anydepthsetStatenotifynotify

    How to read this: nothing in the middle of the component tree is involved. The store is reachable from any component, in any React root, and it keeps its state when every component using it has unmounted.

    That last property is the point and the danger. In the lab a test unmounts the whole UI and mounts a new badge, which still shows the cart. A provider-based cart would have started empty.

    Choosing a home

    Figure 4. A ladder of places for state

    flowchart TD accTitle: Choosing where state should live accDescr: Start with local state in one component. If a sibling needs it, lift it to the closest common parent. If the parent is far away, try composition by passing elements as children. If many distant components in one subtree need it, use a reducer with context. If it must be read outside any subtree or survive all unmounts, use a module-level store or a state library. If it is really server data, the URL or a form, use the tool built for that. A["Local state
    in one component"] -->|"a sibling needs it"| B["Lift to the closest
    common parent"] B -->|"parent is far away"| C["Composition
    pass elements as children"] C -->|"many distant readers
    in one subtree"| D["Reducer + context
    scope = provider"] D -->|"needed outside any subtree,
    or must outlive unmounts"| E["Module store or
    state library"] A -.->|"it is really server data,
    a URL or a form"| F["Use the tool built
    for that kind of state"]

    How to read this: start at the top and move down only when the current rung fails. The dashed arrow is a side exit: much of what teams put in a global store is server data, URL state or form state, each of which has its own lesson in this module.

    The Redux documentation, which makes the strongest case for a central store, still says that using local component state is fine and that deciding what kinds of state make up an application is the developer's job. Its rules of thumb for what belongs in Redux include whether other parts of the application care about the data and whether the same data drives multiple components. A dropdown's "is open" flag matches neither.

    Home Who can read it How long it lives Typical use Main cost
    Local useState The component only While it stays mounted at its position Input text, open/closed, hover Lost on unmount
    Lifted to a parent The parent and its children, through props While the parent stays mounted A selected id, a filter Drilling if the parent is far
    Reducer and context Any component under the provider While the provider stays mounted A cart in one section, a theme Readers re-render on every value change
    Module-level store Any code that imports the module While the page's JavaScript lives Cart badge, session, cross-root state Hidden readers, leaks between tests and requests

    Reach, lifetime and cost

    Three questions settle most placements. Reach: who needs to read it and who needs to change it? Lifetime: when should it reset (unmount, navigation, sign-out, reload)? Cost of a change: how many components re-render when it changes, and how many places can change it?

    The other side of this topic. Back-end systems face the same question as "where does a request's state live": in the process, in a shared store, or in the client. A server that keeps a session in its own memory has made the same trade as a module-level store: easy access, but state that is lost on restart and not shared between instances.

    Build it: watch each rule run

    Goal. Run the placement rules as tests and a Node demo: lifting, redundant and duplicated state, contradictory flags, drilling versus composition, and the lifetimes of local state, a provider and a module store.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It uses React with Testing Library under jsdom, which is a JavaScript model of the DOM and not a browser.

    cd examples/frontend
    pnpm install
    cd labs/local-vs-global-state
    pnpm test           # 23 tests in jsdom
    node src/demo.ts    # pure logic: no React, no DOM

    Steps.

    1. Run the tests and read them in order. Section 1 shows a search box that cannot filter a list beside it, then the lifted version. Sections 2 to 4 each pair a wrong component with a right one. Section 5 compares drilling with composition. Section 6 is the lifetime test of Figure 1. Sections 7 and 8 are the provider and the module store.
    2. In section 8, find the test titled "must be reset between tests". A module-level store keeps its state across tests, so beforeEach has to empty it. A provider needs no such line.
    3. Run the demo and compare it with the output below. Section 1 shows why a stored copy goes stale. Section 4 shows a store continuing to track state after its only subscriber is gone.

    Expected output, captured from a real run (Node 26.13.1, 2026-11-30):

    Local vs global state: the rules, run on plain data
    
    === 1. A stored copy goes stale; an id and a lookup do not
    selected by copy, before rename: Oat milk
    selected by copy, after rename:  Oat milk
    selected by id,   after rename:  Oat drink
    selected by id,   after delete:  (nothing selected)
    
    === 2. Derived values are computed, not stored
    query ""      -> 4 shown: p1 p2 p3 p4
    query "oat"   -> 2 shown: p1 p2
    query "OAT "  -> 2 shown: p1 p2
    query "rye"   -> 1 shown: p3
    query "zzz"   -> 0 shown: -
    
    === 3. The cart reducer is pure
    empty:  {} count 0
    one:    {"p1":1} count 1
    two:    {"p1":2} count 2
    three:  {"p1":2,"p2":1} count 3
    fewer:  {"p2":1} count 1
    older states untouched: true
    
    === 4. A module-level store: subscribers, notifications, lifetime
    badge told: 2 time(s), count now 2
    after the badge is gone: badge told 2 time(s), count still tracked: 3
    after an explicit reset: 0
    
    === 5. Scope: one store per page load, or one per provider
    left cart: 1, right cart: 0

    What the lab does not show. No real browser, so nothing about layout, painting or timing. It does not run server rendering, so the server-side hazard below is described from React's and Zustand's documentation, not demonstrated. Render counts are a measure of how often React called a component function, not a measure of speed.

    Break it. Change your own copy of GlobalAddButton so that it also reads the count with useSyncExternalStore. Run the tests: "a badge that selects the count re-renders when the count changes, and a button does not" fails, because the button now renders on every change. Revert it. This is the cost of subscribing wide: every subscriber is told about every change it selects.

    Stretch. Add a useSelector(store, selector) hook and show that a badge subscribed to one product's quantity ignores additions of other products.

    In practice: a product page whose state all went global

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A storefront's product page grew from one component to about forty. When the team adopted a global store, they moved everything into it for consistency: the cart, the search text, the selected product (as a full object), the open/closed flag of a size guide, and an "is sending" flag for the order button. Typing in the search box feels slow on a mid-range phone, a product renamed by the catalogue service still shows its old name in the sidebar, and about one test in twenty fails depending on test order (all figures illustrative).

    Starting architecture

    Figure 5. Starting point: one global store holds everything

    Starting architecture: every piece of state, from the cart to a dropdown flag, lives in one global storeForty components to Global store (read, write); Global store to Catalogue API (copy of products)Forty components: all subscribeFortycomponentsall subscribeGlobal store: cart, search, flagsGlobal storecart, search,flagsCatalogue API: productsCatalogue APIproductsread, writecopy of products

    How to read this: every arrow into the store is a coupling. The store holds a copy of server data (so it can go stale) and UI details that only one component cares about (so every change notifies many).

    Options considered

    Option What it fixes What it costs Risk
    Keep one global store and add selectors everywhere Fewer re-renders per change Many selectors to write and review State is still copied and still global
    Sort state by owner and reach: local, lifted, provider, store Each fact lives where it is needed, tests need no resets for most of it A migration, and a review of every field Moving a field to the wrong home

    The decision

    Field Decision record
    Context One store holds state with very different reach and lifetime, and it copies data that has another owner.
    Decision Keep only the cart in a store, because the header badge and the product list read it from different parts of the page. Make the search text a lifted useState in the catalogue. Store the selected product's id, and look the object up. Make the size-guide flag local to its component. Replace isSending and isSent with one status value.
    Consequences, good Typing in the search box notifies no cart subscribers. Renames reach the sidebar. Most component tests need no store set-up.
    Consequences, bad State is now spread over several homes, so a new engineer needs the ladder in Figure 4 to know where to look.
    Revisit when A second area, such as saved lists, needs state that crosses subtrees, or the cart must survive a reload. Then reconsider the store's shape or add persistence.

    Rollout and verification

    1. List every field in the store with its readers and writers, and mark each as local, lifted, provider or global by the rules of reach and lifetime.
    2. Move one field at a time, starting with fields that only one component reads. Run the tests after each move.
    3. Replace copies with ids wherever a store holds an object that the catalogue also holds.
    4. Add a test per remaining global field that resets the store, and fail the build if a test file touches the store without a reset.
    5. Compare renders per keystroke in a profile before and after.

    The 2 a.m. failure

    A week after launch, a customer reports seeing "3 items" in the header on a freshly opened page, with an empty cart. Support finds several reports of the same thing. The page is rendered on a server, and the cart store is created at module scope and filled during render with the visitor's cart (illustrative). A server can handle many requests at the same time and a module is loaded once, so the store is shared between visitors. Zustand's documentation says the same for Next.js: the store should be created per request and should not be shared across requests.

    First three checks: (1) reproduce with two requests in flight to the same server instance, and see if the HTML of one contains the other's data; (2) grep for state created at module scope that is written during render or in a server data function; (3) check whether the cache in front of the page keyed the HTML by cookie. Mitigation: stop storing per-visitor data in module-level state on the server; fill the cart on the client after hydration while the fix ships. Follow-up: create the store per request and share it through a provider, add a server-render test with two interleaved requests, and add a rule that module-level stores hold only data that is the same for every visitor.

    Architect's notes

    • Name the owner of each piece of state in the design, along with its reach and lifetime. "The store" is not an owner.
    • Default to local. Move state out only when a named reader needs it.
    • Store ids, not objects, and compute everything derivable. Duplicates turn a placement choice into a consistency bug.
    • Prefer composition to context when the problem is only distance.
    • Make server rendering a first-class check. Anything global on a server is shared between users unless it is created per request.

    Common mistakes

    • Putting everything in the global store "for consistency". The store becomes a second component tree without any of its boundaries.
    • Storing derived data, such as a filtered list or a total, so it falls out of step with its source.
    • Storing a copy of an object that has another owner, such as a server record. It goes stale or outlives the item it describes.
    • Forgetting the lifetime. A global cart that should reset at sign-out but does not, or a local draft that should survive a tab switch but does not.
    • Module-level state on a server. One module instance serves many visitors.

    Key takeaways

    • State is described by owner, scope and lifetime. Local and global differ in all three.
    • Keep state minimal: if you can compute it during render, do not store it. Store an id, not a copy.
    • Lift state to the closest common parent; use composition before context.
    • Reducer plus context shares state across a subtree. Its lifetime is the provider's, and its readers re-render when the value changes.
    • A module-level store is reachable everywhere and lives as long as the page. That reach and lifetime is its cost: hidden readers, test leaks and server sharing.
    • Much of what is called global state is server, URL or form state and should use the tool built for it.
    • Move state up one rung at a time, only when a named need requires it.

    Practice exercises

    Exercise 1 — Starter (45 min): List the state in a page you own. For each item write its owner, who reads it, who changes it, and when it should reset. Mark every item that could be computed or that duplicates another.

    Exercise 2 — Intermediate (2 hours): In the lab, add a "recently viewed" list that the header and the product page both show. First lift it, then try composition, then a provider. Write one test per version, and note which versions survive a tab switch.

    Exercise 3 — Advanced (half day): Extend the lab's module store with a useSelector that avoids re-rendering when the selected slice is unchanged, and write a test that a button which only dispatches never re-renders. Then write the per-request version of the store behind a provider, and test that two interleaved "requests" do not see each other's cart.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments