Redux

Intro

Redux is an open source JS library for managing you application state, it was inspired by Facebooks’ Flux architecture and it is mostly used with libraries such as React, Angular, Nextjs.

It helps in writing applications that behave cohesively, on top of that it provides a great developer experience, such as live code editing combined with a time traveling debugger, Redux in itself is tiny (2kB, including dependencies), but has a large system of addons available.

Redux Toolkit

Redux Toolkit is a official recommended approach for writing Redux logic, it wraps around the Redux core and contains packages that are thought to be essential for building a Redux app.

Ecosystem

Redux is a tiny library, but it’s contracts and APIs are carefully chosen to spawn an ecosystem of tools and extensions, an d the community has created a wife variety of helpful addons, libraries and tools, which are not required to use Redux, but they can make it a lot easier to implement features

Core Concepts

Example of an object:

{
  todos: [{
    text: 'Eat food',
    completed: true
  }, {
    text: 'Exercise',
    completed: false
  }],
  visibilityFilter: 'SHOW_COMPLETED'

To change something in this state, you need to dispatch an action. An action is a plain JS object that describes what happened.

{ type: 'ADD_TODO', text: 'Go to swimming pool' }
{ type: 'TOGGLE_TODO', index: 1 }
{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }

Enforcing that every change is described as an action lets us have a clear understanding of what’s going on in the app, if something is changed we know why it changed. Finally to tie state and actions together, we write a function called a reducer, nothing special, just a function that takes state and action as arguments, and returns the next state of the app.

function visibilityFilter(state = 'SHOW_ALL', action) {
  if (action.type === 'SET_VISIBILITY_FILTER') {
    return action.filter
  } else {
    return state
  }
}

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat([{ text: action.text, completed: false }])
    case 'TOGGLE_TODO':
      return state.map((todo, index) =>
        action.index === index
          ? { text: todo.text, completed: !todo.completed }
          : todo
      )
    default:
      return state
  }

Summary

Redux is a library for managing and updating application state, using events called “actions”. It serves as a centralized store for state that needs to be used across your entire application without the need to send it through the whole child hierarchy and overflowing the hierarchy with repeated data, with rules ensuring that the state can only be updated in a predictable fashion.