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 get 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: '.....'
      }
    ]
  },
];

It is hard to work directly with such a structure for several reasons:

  • It duplicates data inside it, so it is hard to update
  • The logic of reducers gets more complicated the more nesting there is

The correct approach to Redux is to consider it as a relational database. The data inside the repository should be normalized. With this view, we can perceive each slice working with a set of entities as a separate table in the database.

Let's observe the basic principles of organizing data:

  • Each entity should be stored in its reducer
  • A collection of entities of the same type should be stored as an object, where the keys are object identifiers and the values are the objects themselves
  • The order of data in this object should be defined by a separate array consisting only of identifiers
  • Data should refer to each other only by identifiers

Now we will discuss that code example:

{
  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. We store each entity in its reducer. The entities object stores the entities themselves, and the ids object has the identifiers. What advantages have we gained:

  • The data aren't repeated, so 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 coming from the back end isn't usually normalized, as it is convenient for the front end. Therefore, before adding them to the store, we must normalize them first. We can do it 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

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:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

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.