Redux & Redux Toolkit
/Beginner
Three Principles of Redux
Definition
The three fundamental rules that dictate how Redux operates: Single Source of Truth, State is Read-Only, and Changes are made with Pure Functions.
Explain Like I'm New
1. There is only ONE giant object holding all data. 2. You cannot edit that object directly. 3. To change the object, you must write a strict mathematical function (Reducer) that takes the old object, makes a copy, and returns the new copy.
Real World Example
A ledger at a bank. 1. There is only one master ledger. 2. You cannot use an eraser to change past transactions. 3. To update a balance, the accountant must write a brand new line at the bottom of the ledger.
Common Use Cases
- •Understanding the philosophy behind Redux architecture
Interactive Example
/* The 3 Principles in Code: */ // 1. Single Source of Truth (One object holds everything) const store = { user: { name: 'John' }, cart: { items: 3 } }; // 2. State is Read-Only (Never do this!) // store.cart.items = 4; // 3. Changes are made with Pure Functions (Reducers) function reducer(state, action) { if (action.type === 'ADD_TO_CART') { // Return a BRAND NEW object (Immutable update) return { ...state, cart: { items: state.cart.items + 1 } }; } return state; }
Interview Questions
basic
- What does 'Single Source of Truth' mean in Redux?
intermediate
- What is a 'Pure Function'?