Normalized State
Problem
Nested data structures lead to duplicated entities scattered throughout state, causing sync nightmares when updating a single item. Updating a user’s name requires searching through multiple arrays and objects. Deeply nested updates are verbose and error-prone. The same blog post appears in multiple places with different versions, showing inconsistent data to users.
Solution
Store entities by ID in flat lookups rather than nested trees. This eliminates duplication, makes updates simpler, and prevents inconsistencies when the same data appears in multiple places.
Example
This example shows normalized state structure where entities are stored by ID in flat lookup tables, with relationships maintained through ID references.
const state = {
// Users stored by ID for easy lookup and updates
users: {
1: { id: 1, name: 'Alice' },
2: { id: 2, name: 'Bob' }
},
// Posts reference users by ID instead of nesting user objects
posts: {
101: { id: 101, title: 'Hello', authorId: 1 }
}
};
// Update user in one place - all posts referencing it stay consistent
Benefits
- Eliminates data duplication by storing each entity once by ID.
- Makes updates simple and consistent by having a single source of truth.
- Prevents inconsistencies when the same data appears in multiple views.
- Enables efficient lookups and relationships through ID references.
Tradeoffs
- Requires denormalizing data when rendering nested structures.
- Adds complexity with transformation logic between normalized and UI shapes.
- Can make code harder to read with ID lookups instead of direct nesting.
- May not be worth the complexity for simple applications with minimal data reuse.