</it pathshaala>
×

Normalizing Data in Redux State in React JS

In complex applications, especially those dealing with large datasets or relational data (e.g., lists of users, posts, or comments), it is essential to store data in an optimized and structured format. One way to achieve this is through normalization—a technique used to store data in a flat structure where entities are stored as key-value pairs.

In Redux, normalizing data helps prevent redundancy, simplifies updates, and makes it easier to manage relationships between different types of data. In this article, we'll explore the concept of normalizing data in Redux state, how to implement it, and why it's useful.

1. What is Data Normalization?

Data normalization is the process of restructuring your data to remove redundant information. In a normalized state, each unique entity is stored only once, and relationships between entities are represented by their unique identifiers (IDs) rather than storing all data inline.

For example, consider a scenario where you have a list of posts, and each post has an associated author. In a normalized state, you would store the posts and authors separately, linking them via the author's ID instead of embedding the entire author object in each post.

2. Why Normalize Data in Redux?

Normalizing data in Redux state has several advantages:

  • Prevents Redundancy: When data is normalized, you avoid storing the same data multiple times. This reduces memory usage and ensures consistency.
  • Simplifies Updates: When a piece of data needs to be updated (e.g., changing an author's name), it only needs to be updated in one place, not across every post that references that author.
  • Improves Performance: Normalized data is easier to query and update, which can lead to performance improvements, especially in large applications with complex state trees.

3. Normalizing Data with Redux Toolkit

Redux Toolkit doesn't directly provide utilities for normalizing data, but we can use libraries like normalizr to help with this process. normalizr is a library that facilitates the normalization of nested JSON data by defining schemas for your data.

Example 1: Installing Normalizr

        
          npm install normalizr
        
      

After installing normalizr, you can define schemas and normalize your data. Here's an example where we normalize a list of posts, each with an author.

4. Example: Normalizing Posts and Authors

Let's imagine we are fetching a list of posts from an API, where each post contains an embedded author object. Instead of storing the author information inside each post, we'll normalize the data and store the posts and authors separately.

Example 2: Normalizing Posts and Authors

        
          import { createSlice } from '@reduxjs/toolkit';
          import { normalize, schema } from 'normalizr';

          // Define schemas for posts and authors
          const author = new schema.Entity('authors');
          const post = new schema.Entity('posts', {
            author: author
          });

          // Example data fetched from an API
          const data = {
            id: 1,
            title: 'Post 1',
            author: { id: 1, name: 'John Doe' }
          };

          // Normalize the data
          const normalizedData = normalize(data, post);

          // Create a slice to manage posts and authors
          const dataSlice = createSlice({
            name: 'data',
            initialState: {
              posts: {},
              authors: {},
            },
            reducers: {
              setData: (state, action) => {
                state.posts = action.payload.entities.posts;
                state.authors = action.payload.entities.authors;
              }
            }
          });

          // Export the setData action
          export const { setData } = dataSlice.actions;

          // Export the reducer
          export default dataSlice.reducer;
        
      

In this example:

  • normalizr is used to define the schema for the post and author data.
  • The normalize function flattens the data into entities, where posts and authors are stored separately in a normalized structure.
  • The setData action is used to store the normalized data in the Redux state.

5. Using the Normalized Data in React Components

Once the data is normalized and stored in the Redux state, you can access it in your React components using the useSelector hook. The posts will reference the authors by ID, and you can easily access the full author details when needed.

Example 3: Displaying Posts and Authors

        
          import React from 'react';
          import { useSelector } from 'react-redux';

          const Posts = () => {
            const posts = useSelector((state) => state.data.posts);
            const authors = useSelector((state) => state.data.authors);

            return (
              

Posts

{Object.values(posts).map((post) => (

{post.title}

Author: {authors[post.author].name}

))}
); }; export default Posts;

In this component:

  • useSelector is used to select both posts and authors from the Redux state.
  • The posts are mapped over, and for each post, the corresponding author is retrieved from the authors object using the author's ID.

6. Benefits of Normalizing Data in Redux

Normalizing data in Redux provides the following benefits:

  • Reduced Redundancy: Storing entities once instead of repeatedly avoids data duplication and ensures consistency.
  • Easier Updates: When an entity changes, you only need to update it in one place in the state, which makes managing updates more straightforward.
  • Better Performance: A normalized state is easier to query and navigate, which can improve performance, especially in large applications with many relationships.

7. Conclusion

Normalizing data in Redux state helps manage complex or relational data more efficiently by storing entities in a flat structure. By using libraries like normalizr, you can reduce redundancy, simplify updates, and improve performance. This is especially useful when working with large datasets or handling complex relationships between entities.

Redux Toolkit combined with normalizr makes it easy to manage normalized data in a Redux store, providing a more scalable and maintainable approach to state management in React applications.





Advertisement