Redux - Core Concepts

Core building blocks

  • Action: plain object describing what happened, e.g. { type: 'todo/add', payload: 'Buy milk' }
  • Reducer: pure function that returns new state given current state and action.
  • Store: holds state, dispatches actions, and notifies subscribers.

Try it: Todo reducer (immutable updates)

View source
const { createStore } = Redux;
const initial = { todos: [] };
function todosReducer(state = initial, action){
  switch(action.type){
    case 'todo/add':
      return { ...state, todos: [...state.todos, { id: Date.now(), text: action.payload, done: false }] };
    case 'todo/toggle':
      return { ...state, todos: state.todos.map(t => t.id===action.payload ? { ...t, done: !t.done } : t) };
    default: return state;
  }
}
const store = createStore(todosReducer);
function render(){
  const s = store.getState();
  document.getElementById('todos-out').textContent = JSON.stringify(s.todos);
}
store.subscribe(render); render();
function addTodo(){ const v = document.getElementById('todo-input').value.trim(); if(!v) return; store.dispatch({type:'todo/add', payload:v}); document.getElementById('todo-input').value=''; }
function toggleFirst(){ const s = store.getState(); const first = s.todos[0]; if(first) store.dispatch({type:'todo/toggle', payload:first.id}); }

Syntax primer

  • Never mutate arrays/objects in reducers; return new copies with updated fields.
  • Use ... spread to copy arrays/objects.