Skip to content

    Frontend System Design

    Derived and Normalized State

    Learn to derive values instead of storing them, flatten nested API data into one table per entity, and use memoised selectors so one change updates every view.

    By Published 12 min read

    • frontend-system-design
    • derived-state
    • normalization
    • selectors
    • state-management
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Local vs Global State

    What you'll learn: By the end of this lesson you will be able to tell stored state from derived state and compute the second instead of saving it, flatten a nested API response into one table per entity, update one fact in one place, write selectors that rebuild what a screen needs, and explain why a memoised selector depends on immutable updates.

    Think of a spreadsheet. The "Total" cell holds a formula, not a number someone typed. Change a price and the total follows, because it was never a separate fact. Now think of an address book where one friend's phone number is copied onto five pages. When they move, you update four pages and the fifth quietly lies. Those two pictures are this lesson: derive what can be computed, and store each fact once.

    The running example is an orders screen for a grocery marketplace. The API returns orders with their lines, each line carrying its own copy of the product (name, price) and the customer; the screen shows a list of orders, an order's total, and the revenue of open orders. The numbers and names in the lab are illustrative.

    The core idea

    1. Store the smallest set of facts; derive the rest. react.dev's rule: if you can calculate some information from props or existing state during rendering, you should not put it in state. A stored copy is a second fact that can disagree with the first.
    2. Store each entity once, under its id. Nested data that repeats the same product in many places makes an update a search-and-replace, and Redux's guide lists exactly that as the reason to normalise: duplicated data is harder to update correctly, and deep updates get complicated.
    3. Updates return new objects and share what did not change. That makes "did this change?" a cheap reference comparison, which is what lets a cached derivation know when to recompute.

    Derive, do not store

    react.dev's Choosing the State Structure lists five principles: group related state, avoid contradictions, avoid redundant state, avoid duplication and avoid deeply nested state. The third is the heart of this section, and its standard example is a value that can be computed, such as a full name from a first and last name.

    Illustration 1: the minimal example

    A common version of duplication is keeping the selected object next to the list it came from. react.dev's fix is to keep the id and derive the object during render:

    const [items, setItems] = useState(initialItems);
    const [selectedId, setSelectedId] = useState<string | null>(null);
    
    const selected = items.find((item) => item.id === selectedId); // derived, not stored

    If the selected item's title is edited, selected is correct on the next render with no extra code, because there is only one copy to edit. The same page says that for selection you should keep the id or index in state, not the object.

    Figure 1. Store it or derive it?

    flowchart TD accTitle: Deciding whether a value is state or derived accDescr: A decision tree. If a value can be calculated from existing props or state, derive it during render, and memoise only if measured to be expensive. If it is a copy of something stored elsewhere, store an id instead. Otherwise it is real state. A{"Can it be calculated from
    existing state or props?"} A -->|"yes"| B["Derive it during render
    (memoise only if it is slow)"] A -->|"no"| C{"Is it a copy of something
    stored elsewhere?"} C -->|"yes"| D["Store the id and look it up"] C -->|"no"| E["It is real state"]

    How to read this: the questions run from cheapest to most expensive to get wrong. A derived value cannot go stale; a copy can.

    react.dev's You Might Not Need an Effect gives the same advice from the other side: do not mirror state with an effect that calls a setter; calculate during rendering, which avoids extra cascading updates and out-of-sync state variables. It also says that unless you are creating or looping over thousands of objects a calculation is probably not expensive, and suggests measuring (it gives 1 ms of total logged time as a rough threshold) before reaching for useMemo.

    Why nested API data hurts

    An API often returns a tree: orders contain lines, lines contain products, and every line has its own copy of its product. That is convenient to send and awkward to keep. The Redux guide gives three costs: duplicated data is hard to keep consistent; nested data forces nested reducer logic; and because an immutable update must copy every ancestor of the changed object, an update to a deep object produces new references all the way up, which can make unrelated components that read those references re-render.

    The lab makes the sizes concrete. Its sample is three orders sharing one tea product and one mug. The numbers below come from the lab's demo (full output further down):

    • Nested: 3 separate copies of product P-tea, 23 objects and arrays in total.
    • Renaming the product correctly in the nested payload makes 14 new objects and arrays; in the normalised state it makes 4.
    • A "rename the first copy it finds" update leaves the copies disagreeing: one order shows the new name and two show the old.

    The normalised shape

    Redux's guide says to treat a portion of the store as a database. Each type of data gets its own table; a table holds items by id; references between items store ids; and arrays of ids give ordering. The names byId and allIds are the guide's own.

    Figure 2. One table per entity, references by id

    erDiagram accTitle: Normalised order state accDescr: Four tables. An order belongs to one customer and lists several lines. Each line refers to one product and holds a quantity. A product is stored once, however many lines use it. No table stores a total. ORDER }o--|| CUSTOMER : "customerId" ORDER ||--o{ LINE : "lineIds" LINE }o--|| PRODUCT : "productId" ORDER { string id string status } LINE { string id number quantity } PRODUCT { string id string name number priceCents } CUSTOMER { string id string name }

    How to read this: this is the stored shape, one object per thing. Notice what is missing: no table has a "total". A total is a derived value.

    The lab's normalize() walks the nested payload once. Every customer, product, line and order is added to its table, parents keep ids of their children, and the server's totalCents is dropped on purpose, since it can be computed from lines and prices.

    Figure 3. From payload to screen

    Normalise once, derive on every readAPI payload to normalize(); normalize() to State tables (tables); State tables to Selectors (read); Selectors to Screen (view)API payload: nested, repeated copiesAPI payloadnested, repeatedcopiesnormalize(): one object per idnormalize()one object per idState tables: byId + allIdsState tablesbyId + allIdsSelectors: joins and totalsSelectorsjoins and totalsScreen: what the user readsScreenwhat the userreadstablesreadview

    How to read this: the accent boxes are your code. The store holds only facts; everything the screen shows beyond them is computed on the way out.

    Illustration 2: the realistic example, from the lab

    The demo runs the same sample through both shapes. Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/derived-and-normalized-state, copied from examples/frontend/golden/derived-and-normalized-state.txt), in full:

    === 1. the same data, two shapes
    nested payload : 3 orders, 3 separate copies of product P-tea, 23 objects and arrays in total
    normalised     : 3 products (P-tea stored once), 6 lines, 3 orders, 2 customers, 30 objects and arrays in total
    stored tables  : customers, products, lines, orders
    order O-100    : {"id":"O-100","status":"open","customerId":"C-1","lineIds":["L-1","L-2"]}
    
    === 2. rename product P-tea to 'Loose-leaf tea'
    nested     : 14 objects and arrays are new
    normalised : 4 objects and arrays are new
    normalised, tables whose reference is unchanged: customers, lines, orders
    every order now shows: Loose-leaf tea | Loose-leaf tea | Loose-leaf tea
    
    === 3. the nested shape allows a half-done rename
    product ids whose copies disagree: ["P-tea"]
    names of P-tea across the three orders: Loose-leaf tea | Tea sampler | Tea sampler
    in the normalised state there is one P-tea object, so there is no second copy to forget
    
    === 4. a stored total goes stale; a derived total does not
    O-100 before the change     : $25.00
    stored total after 2 -> 5   : $25.00   (still the old number)
    derived total after 2 -> 5  : $44.50
    
    === 5. a selector that recomputes only when its inputs change
    initial state            open revenue  $42.00   recomputations so far: 1
    same state again         open revenue  $42.00   recomputations so far: 1
    rename customer C-1      open revenue  $42.00   recomputations so far: 1
    rename product P-tea     open revenue  $42.00   recomputations so far: 2
    set L-1 quantity to 5    open revenue  $61.50   recomputations so far: 3

    Block 2 is the argument for normalising in numbers. Renaming P-tea replaces one entry in one table: products is new and customers, lines and orders keep their old references, so a component reading only those has nothing to re-render. Block 5 shows why that matters beyond style: the open-revenue selector recomputed only when the tables it reads changed. Renaming a customer left it at 1 recomputation; renaming a product made 2; a quantity change made 3.

    Selectors: derive on the way out

    The screen rarely wants the flat shape. A selector is a function from state to a value the screen needs; the Redux guide defines it as any function that accepts the state, or part of it, and returns data based on it. selectOrderView in the lab rebuilds the nested shape for display only (an order with its customer's name and line names) from the flat tables. selectOrderTotalCents sums quantity times price over the order's lines. Neither result is stored.

    Block 4 shows why not storing the total matters. After a line's quantity changes from 2 to 5, the stored total is still $25.00, while the derived total is $44.50. A derived value follows its inputs automatically.

    Memoising a selector

    A derivation that loops over many items can be cached. The Redux guide describes memoisation as tracking a function's inputs and, when called with the same inputs, returning the previous result; its createSelector compares the results of its input selectors with === and re-runs the result function only if one differs. The lab writes the same idea out in a few lines, memoiseLast, so the rule is visible: the cache key is the identity of the input tables.

    That is why immutability is not optional. react.dev says to treat any object in state as read-only, and notes that spread is shallow: it copies one level, so a nested update needs one spread per level. A mutated table keeps its reference, so a memoised selector would keep returning the old answer; the lab has a test that shows exactly that.

    The Redux guide adds the mirror-image warning: a selector that always returns a new array (a filter() or map() in the selector itself) forces a re-render each time, because useSelector compares by reference. Memoise such derivations, or derive them in the component.

    When not to normalise

    Normalising costs ids, joins and a normalize() step. Do not pay it for a small list that is read, shown and replaced as a whole, for data that never repeats, or for a value used by exactly one component. The signal to normalise is the same entity appearing in more than one place, or an update that has to touch more than one copy. Server-state caching is its own topic, covered by a planned lesson in this module.

    The other side of this topic

    On the back end, a relational database stores each fact once and joins on demand, and the same trade-off appears there: fewer places to update, more work at read time. The client version is smaller, because the "joins" are selectors running over data already in memory.

    Trade-offs

    Choice Gain Cost
    Derive totals and joins Never stale; less code to keep in sync Compute on read
    Store the derived value No recompute A second fact that can disagree
    Normalise One update, no disagreeing copies, fewer new references normalize(), ids, selectors to rebuild views
    Keep the nested tree Simple to render Duplicated copies; deep updates
    Memoised selector Skips work on unchanged inputs Needs immutable updates; key is reference identity

    Build it

    The lab examples/frontend/labs/derived-and-normalized-state has src/normalize.ts, src/selectors.ts (including memoiseLast), src/reducers.ts (the normalised updates next to the nested ones, including the careless variants), src/identity.ts (counts new objects) and src/demo.ts. It uses no clock and no randomness.

    cd examples/frontend/labs/derived-and-normalized-state
    ../../node_modules/.bin/vitest run
    node src/demo.ts

    Verified. The 19 tests passed with Node 26.13.1 and Vitest 5.1.0, the type check passed, and node examples/frontend/tools/capture-golden.mjs --check confirms the demo output equals the golden file. They cover normalising, selectors and the stale-total contrast, structural sharing, the half-done nested rename, and memoised selectors including the mutation case.

    Break it. In src/selectors.ts, temporarily make the comparison inside memoiseLast always report a difference (for example false && Object.is(x, lastInputs![i])). Three tests fail: the recomputation count, the identical-result test and the mutation test, because the cache never hits. Restore the line and re-run.

    Stretch. Add an addLine reducer that touches only the line table and the order, and write a test that counts the new objects.

    In practice: an orders screen where one rename showed three names

    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

    An orders screen stores the API's nested response in component state. Each order carries a totalCents from the server. Support reports two bugs: after a product is renamed in an admin edit, some orders show the new name and others the old; and after a quantity is changed in the browser, the order total does not move until the page reloads.

    Starting architecture

    Figure 4. A nested copy with a stored total

    Starting architecture: store the response, store the totalOrders API to Nested state; Nested state to Stored total (never recomputed); Nested state to Orders screenOrders API: nested responseOrders APInested responseNested state: product copied per lineNested stateproduct copiedper lineStored total: from the serverStored totalfrom the serverOrders screen: shows what is storedOrders screenshows what isstorednever recomputed

    How to read this: the warning boxes are the two bugs. Copies of the product live in many lines, and the total is a stored fact that nothing updates.

    Options considered

    Option What it fixes What it costs Risk
    Patch every copy on each edit Names Search-and-replace in every handler A missed copy
    Recompute the total in each handler that edits a quantity Totals Logic in many places A missed handler
    Normalise once, derive totals and views with selectors Both bugs at the root A normalize() step and selectors Ids must be stable

    The decision

    Field Decision record
    Context Duplicated product copies drift apart, and a stored total goes stale.
    Decision Normalise the response into tables by id on arrival, drop the server's total, derive totals and the display shape with selectors, and memoise only the revenue selector.
    Consequences, good One update changes a name everywhere; totals follow quantities; unrelated components keep their references.
    Consequences, bad Another layer to learn; the display shape is rebuilt on read.
    Revisit when A server-state cache already provides stable identities, or the list is small enough to skip normalising.

    Rollout and verification

    1. Reproduce both bugs in tests (rename one copy, change a quantity) before changing the shape.
    2. Introduce normalize() at the boundary and keep the old components reading through selectors.
    3. Assert references: after a rename, the unrelated tables keep their old references.
    4. Compare totals from selectors with the server's on a sample of real orders before removing the stored one.

    The 2 a.m. failure

    A new bulk-import endpoint returns lines whose product has the same id but a different price from the one already stored. normalize() keeps the later copy ("the later copy wins"), so every earlier line of that product silently reprices, and totals change on orders the user was not looking at.

    First three checks: (1) log when normalize() receives two different values for one id; (2) compare the new payload's prices with the stored ones; (3) check whether line prices should be frozen at purchase time. Mitigation: stop merging that endpoint's products into the shared table. Follow-up: model "price at purchase" as a field of the line, not a lookup into the product, and add a test with conflicting copies.

    Architect's notes

    • Normalise at the boundary, once. Components see tables and selectors, never the raw tree.
    • Never store what you can compute. If you must cache, memoise the selector, not the state.
    • Decide what is a fact and what is a lookup. A price at purchase is a fact of the line; a product's current name is a lookup.
    • Immutability is the contract. Memoisation, cheap change detection and structural sharing all depend on it.
    • Do not normalise by reflex. Do it when an entity repeats or an update must touch several places.

    Common mistakes

    • Storing a value you could derive, such as a total, a count or a selected object.
    • Mirroring state with an effect that sets a second state variable.
    • Updating one copy of a duplicated entity and forgetting the rest.
    • Mutating a table that a memoised selector reads.
    • A selector that returns a new array every time, so it always re-renders.
    • Treating "later copy wins" as harmless when two sources can disagree.
    • Normalising everything when a small list would do.

    Key takeaways

    • Store facts once; derive everything that can be computed from them.
    • Keep ids, not copies: selection, references and relationships are ids.
    • Normalised state is one table per entity, byId plus allIds, with no stored totals.
    • A rename touches one entry in one table, so unrelated references do not change.
    • Selectors rebuild the shape the screen needs; memoise them on the identity of their input tables.
    • Memoisation only works with immutable updates.
    • Normalise when entities repeat; skip it for small, whole-replaced data.

    Practice exercises

    Exercise 1: Starter (30 min). Find a stored value in a component you know that is computable from other state, and write the derived version.

    Exercise 2: Intermediate (2 hours). Run the demo, then add a second customer rename and predict how many recomputations openRevenue reports before you run it.

    Exercise 3: Intermediate (2 hours). Add selectCustomerOrders(state, customerId) and a test that the result is the same reference when an unrelated table changes, using memoiseLast.

    Exercise 4: Advanced (half day). Make normalize() report conflicting copies of one id, and decide what the UI should do about them.

    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