Register to get access to free programming courses with interactive exercises

Reducers JS: Redux (React)

Everything that's stored in storage is called a state, but not all states are equally useful. Here's the classification introduced by the Redux documentation:

  • Domain data – application data that needs to be displayed, used and modified. For example, a list of users downloaded from the server.
  • App state – data that determines the behavior of the application. For example, the current open URL.
  • UI state – data that determines how the UI looks. For example, displaying a list in tile view.

Since the store is the core of the application, the data inside it should be described in terms of domain data and app state, but not as a tree of UI components. For example, this way of generating a state state.leftPane.todoList.todos is a bad idea. It's extremely rare for a component tree to reflect directly on a state structure, and that's okay. The view depends on the data, not the data on the view.

A typical state structure looks like this:

{
    domainData1 : {}, // todos
    domainData2 : {}, // comments
    appState1 : {},
    appState2 : {},
    uiState1 : {},
    uiState2 : {},
}

More details about working with UI states will be described in the corresponding lesson.

As mentioned in the JS: React, course, the state structure should resemble a database. Everything should be as flat and normalized as possible.

{
  todos: [
    { id: 1, name: 'why?' },
    { id: 3, name: 'who?' },
  ],
  comments: [
    { id: 23, todoId: 3, text: 'great!' },
  ],
}

With this sort of structure, it's extremely easy to write a reaction to actions, update, add, and delete data. There's very little nesting, everything is nice and simple. But there is one other problem (which we'll always have to deal with). As the number of entities grows, the reducer starts to get quite hefty. It becomes a huge piece of code that does everything. To solve this problem, Redux has a built-in mechanism that allows you to create multiple reducers and combine them with each other. It works like this: each top-level property gets its own reducer, and then they're combined using the combineReducers() function into a root reducer, which is then used to create the store.

import { combineReducers, createStore } from 'redux';

const todosReducer = (state = [], action) => {
  // data from todos will go here
};

const commentsReducer = (state = [], action) => {
  // data from comments will go here
};

const rootReducer = combineReducers({
  todos: todosReducer,
  comments: commentsReducer,
});
const store = createStore(rootReducer);

// If we call reducers as properties in the state, then the code can be shortened:
// const todos = (state = [], action) => { ... };
// const comments = (state = [], action) => { ... };
// const rootReducer = combineReducers({ todos, comments });

The state comes to each reducer, but not the store's entire state, only the part that's found in the corresponding property. Make sure to keep this in mind.

Redux Reducer Combination

Reducers can even be nested, and no special tools are needed to do so, they're ordinary functions that take data as input and return new data. If you use this approach, one feature will appear that can seem frightening at first. Since each reducer has access only to its own part of the state, actions that cause changes in several places at once will be repeated in different reducers:

const todos = (state = {}, action) => {
  switch (action.type) {
    case 'TODO_REMOVE':
      // ...
  }
};

const comments = (state = {}, action) => {
  switch (action.type) {
    // When deleting a ToDo, make sure to remove all of its comments
    case 'TODO_REMOVE':
      // ...
  }
};

In other words, the correct approach is to repeat the part of the case in the necessary reducers, and not to try to get the missing parts of the state.


Recommended materials

  1. Normalizing state shape

Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.