end video

This lesson is only accessible in the paid version of the course.

Get access to all lessons 💫 price: 34.99$

If you already have an account click here.

§ Redux - the predictable state container that looks a lot like a state machine

Now that we are familiar with the concept of a state machine, we can discuss Redux. Redux gained popularity with the rise of the React.js library, where it played a central role. In many ways, Redux resembles a state machine. By definition Redux is made of reducers and a reducer is a function that takes in the current state and an action, and returns a new state.

Redux is originally made as a popular state management library for JavaScript that was developed to help manage complex data structures. It enforces a unidirectional data flow and allows us to manage global state with ease. In this lesson we are looking at the main concepts behind Redux. Not the actual library.

To understand how Redux works, we can think of it as a store that holds the current state of our application, and the only way to modify this state is by dispatching an action. An action is an object that describes what happened in our system. A reducer function, on the other hand, takes the current state and the action, and returns the next state.

Here's a simple example:

const initialState = { count: 0 };

function reducer(state = initialState, action) {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    case "DECREMENT":
      return { count: state.count - 1 };
      return state;

const store = {
  _data: initialState,
  dispatch(action) {
    this._data = reducer(this._data, action);
  getState() {
    return this._data;

store.dispatch({ type: "INCREMENT" });
store.dispatch({ type: "INCREMENT" });

console.log(store.getState()); // { count: 2 }

In this example, we created a reducer function that takes the current state and an action, and returns the next state based on the type of the action. The store is using the reducer, and has a dispatch method.



Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.



Materials related to the lesson:
Files associated with the lesson


Next: Communicating sequential processes(07:02)

To the lesson →