Register to get access to free programming courses with interactive exercises

Data Normalization in Redux React: Redux Toolkit

Most applications work with data that has a nested structure. For example, blog posts have an author and comments. Comments also have authors and can have likes.

const blogPosts = [
  {
    id: 'post1',
    author: { username: 'user1', name: 'User 1' },
    body: '......',
    comments: [
      {
        id: 'comment1',
        author: { username: 'user2', name: 'User 2' },
        comment: '.....'
      },
      {
        id: 'comment2',
        author: { username: 'user3', name: 'User 3' },
        comment: '.....'
      }
    ]
  },
];

Working directly with such a structure is difficult for several reasons:

  • It duplicates data inside it, such as author. This makes it difficult to update
  • Reducer logic gets more complicated the more nesting there is

The correct approach when working with Redux is to think of it as a relational database. The data inside the store must be normalized. In this way, each slice working with a set of entities can be seen as a separate table in the database.

The basic principles of organizing data in the store:

  • Each entity is stored in its own reducer.
  • A collection of entities of the same type is stored as an object, where the keys are object identifiers and the values are the objects themselves.
  • The order of data in this object is defined by a separate array consisting only of identifiers.
  • Data refer to each other only by identifiers.
{
  posts: {
    entities: {
      post1: {
        id: 'post1',
        author: 'user1',
        body: '......',
        comments: ['comment1', 'comment2'],
      },
      post2: {
        id: 'post2',
        author: 'user2',
        body: '......',
        comments: [],
      },
    },
    ids: ['post1', 'post2'],
  },
  comments: {
    entities: {
      comment1: {
        id: 'comment1',
        author: 'user2',
        comment: '.....',
      },
      comment2: {
        id: 'comment2',
        author: 'user3',
        comment: '.....',
      },
    },
    ids: ['comment1', 'comment2'],
  },
  users: {
    entities: {
      user1: {
        id: 'user1',
        username: 'user1',
        name: 'User 1',
      },
      user2: {
        id: 'user2',
        username: 'user2',
        name: 'User 2',
      },
      user3: {
        id: 'user3',
        username: 'user3',
        name: 'User 3',
      },
    },
    ids: ['user1', 'user2', 'user3'],
  }
}

The data are now normalized. Each entity is stored in its own reducer. The entities object stores the entities themselves and the ids store the identifiers. What advantages have we gained?

  • The data aren't repeated, which means that if you want to make a change, you only need to do so in one place.
  • Reducers are not nested
  • Data in this form are easy to retrieve and modify

Now let's see what it looks like inside the slices:

const slice = createSlice({
  name: 'users',
  initialState: {
    ids: [],
    entities: {},
  },
  reducers: {
    addUser(state, action) {
      const { user } = action.payload;

      state.entities[user.id] = user;
      state.ids.push(user.id);
    },
    removeUser(state, action) {
      const { userId } = action.payload;

      delete state.entities[userId];
      state.ids = state.ids.filter((id) => id !== userId);
    },
    updateUser(state, action) {
      const { userId, data } = action.payload;

      Object.assign(state.entities[userId], data);
    }
  },
});

dispatch(addUser({ user }));
dispatch(removeUser({ userId }));
dispatch(updateUser({ userId, data }));

normalizr

The data that come from the backend isn't usually normalized, as it's convenient for the frontend. Therefore, before adding them to the store, you must first carry out normalization. This can be done either by manually traversing the collection and converting it to the desired object, or by using the normalizr library.


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.