• Redux is one of the most trending libraries for front-end development in today’s marketplace.
  • There are three principles in redux:
    • Single source of truth
    • State is read-only
    • Changes are made with pure functions

Single source of truth:

  • The entire application is stored in an object/ state tree within a single store.
  • It debugs or inspects the application and easier to keep track of changes over time.
  • It has been traditionally difficult to implement – Undo/Redo.
  • If all of your states is stored in a single tree, it can be suddenly trivial to implement.

For example,

console.log(store.getState())

/* Prints
{
  visibilityFilter: 'SHOW_ALL',
  todos: [
    {
      text: 'Consider using Redux',
      completed: true,
    },
    {
      text: 'Keep all state in a single tree',
      completed: false
    }
  ]
}
*/

State is read-only:

  • The only way to change the state is to emit an action, an object describing what happened.
  • It ensures that neither the views nor the network callbacks will ever write directly to the state.
  • All changes are centralized and happen one by one in a strict order, there are no subtle race conditions to watch out for.
  • The minimal representation of data is just like state, the action is the minimal representation of the change to that data.

For example,

store.dispatch({
type: 'COMPLETE_TODO',
index: 1
})

store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: 'SHOW_COMPLETED'
})

Changes are made with pure functions:

  • To specify how the state tree is transformed by actions, you write pure reducers.
  • Pure functions are those whose return value depends solely on the values of their arguments.
  • Reducers are just functions, you can control the order in which they are called, pass additional data, or even make reusable reducers for common tasks such as pagination.

For example,

function visibilityFilter(state = 'SHOW_ALL', action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter
default:
return state
}
}

function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
{
text: action.text,
completed: false
}
]
case 'COMPLETE_TODO':
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: true
})
}
return todo
})
default:
return state
}
}

import { combineReducers, createStore } from 'redux'
const reducer = combineReducers({ visibilityFilter, todos })
const store = createStore(reducer)

Categorized in: