only source of information for the store • Must be plain JavaScript object • Must have a type property { type: 'ADD_TODO', text: 'Build my first Redux app' }
non-pure functions) • Consider the state as immutable (don’t mutate the state) function todos(state = [], action) { if (action.type === 'ADD_TODO') { const newState = state newState.push({ text: action.text, completed: false }) return newState } return state } BAD
{}, {}] state newState newState === state ? newState.push({}) Something changed, update the view! Nothing happened! State Mutation Something changed, update the view! true
non-pure functions) • Consider the state as immutable (don’t mutate the state) function todos(state = [], action) { if (action.type === 'ADD_TODO') { const newState = state newState.push({ text: action.text, completed: false }) return newState } return state } BAD
via store.getState() • Allows state to be updated via store.dispatch(action) • Registers listeners via store.subscribe(listener) • It returns a function to unsubscribe the listener
= combineReducers({ visibilityFilter, todos }) const store = createStore(todoApp) store.dispatch({ type: 'ADD_TODO', text: 'Consider using Redux' }) store.dispatch({ type: 'ADD_TODO', text: 'Keep all state in a single tree' }) store.dispatch({ type: 'TOGGLE_TODO', index: 0 }) store.getState()
= combineReducers({ visibilityFilter, todos }) const addTodo = (text) => ({ type: 'ADD_TODO', text }) const toggleTodo = (index) => ({ type: 'TOGGLE_TODO', index }) const store = createStore(todoApp) store.dispatch(addTodo('Consider using Redux')) store.dispatch(addTodo('Keep all state in a single tree')) store.dispatch(toggleTodo(0)) store.getState()
Redux', completed: true, }, { text: 'Keep all state in a single tree', completed: false } ] } import { combineReducers, createStore } from 'redux' const todoApp = combineReducers({ visibilityFilter, todos }) const addTodo = (text) => ({ type: 'ADD_TODO', text }) const toggleTodo = (index) => ({ type: 'TOGGLE_TODO', index }) const store = createStore(todoApp) store.dispatch(addTodo('Consider using Redux')) store.dispatch(addTodo('Keep all state in a single tree')) store.dispatch(toggleTodo(0)) store.getState()