Managing State with Redux in React.js: A Comprehensive Example

Redux is a powerful state management library that works seamlessly with React.js to handle complex application states in a predictable and organized manner. In this article, we will explore a step-by-step example of how to integrate Redux into a React.js application to manage state efficiently. We will build a simple task list app to demonstrate the concepts of Redux in action.

Prerequisites:

Before proceeding with the example, ensure you have Node.js and npm (Node Package Manager) installed on your system. Also, a basic understanding of React.js and JavaScript is recommended.

Step 1: Setting Up the Project

Let’s start by creating a new React.js project using Create React App. Open your terminal and run the following command:

npx create-react-app redux-task-list
cd redux-task-list

Step 2: Installing Redux Packages

Next, install the necessary packages for Redux integration:

npm install redux react-redux

Step 3: Defining the Redux Store

In your project’s src directory, create a new folder named redux and within it, create a file named store.js. This is where we will define our Redux store.

// src/redux/store.js

import { createStore } from 'redux';
import rootReducer from './reducers';

const store = createStore(rootReducer);

export default store;

Step 4: Creating the Reducers

Inside the redux folder, create another folder named reducers. In this example, we will have a single reducer responsible for managing the task list.

// src/redux/reducers/taskReducer.js

const initialState = {
  tasks: [],
};

const taskReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_TASK':
      return {
        ...state,
        tasks: [...state.tasks, action.payload],
      };
    case 'REMOVE_TASK':
      return {
        ...state,
        tasks: state.tasks.filter((task) => task.id !== action.payload),
      };
    default:
      return state;
  }
};

export default taskReducer;

Step 5: Combining Reducers with combineReducers

Since we might have multiple reducers in a larger application, we need to combine them into a single root reducer. Create a file named index.js inside the reducers folder.

// src/redux/reducers/index.js

import { combineReducers } from 'redux';
import taskReducer from './taskReducer';

const rootReducer = combineReducers({
  task: taskReducer,
});

export default rootReducer;

Step 6: Creating Action Creators

Action creators are functions that create actions, which are objects containing a type and an optional payload. Create a file named taskActions.js inside the redux folder.

// src/redux/taskActions.js

export const addTask = (task) => {
  return {
    type: 'ADD_TASK',
    payload: task,
  };
};

export const removeTask = (taskId) => {
  return {
    type: 'REMOVE_TASK',
    payload: taskId,
  };
};

Step 7: Integrating Redux into the React App

Now, let’s modify our App.js component to integrate Redux. We’ll use react-redux to connect our components to the Redux store.

// src/App.js

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { addTask, removeTask } from './redux/taskActions';

function App() {
  const tasks = useSelector((state) => state.task.tasks);
  const dispatch = useDispatch();

  const handleAddTask = (taskName) => {
    const newTask = { id: Date.now(), name: taskName };
    dispatch(addTask(newTask));
  };

  const handleRemoveTask = (taskId) => {
    dispatch(removeTask(taskId));
  };

  return (
    <div>
      <h1>Task List</h1>
      <ul>
        {tasks.map((task) => (
          <li key={task.id}>
            {task.name}
            <button onClick={() => handleRemoveTask(task.id)}>Remove</button>
          </li>
        ))}
      </ul>
      <input
        type="text"
        placeholder="Enter task name..."
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            handleAddTask(e.target.value);
            e.target.value = '';
          }
        }}
      />
    </div>
  );
}

export default App;

Conclusion:

In this article, we’ve walked through a practical example of integrating Redux into a React.js application. We set up the Redux store, created reducers, defined action creators, and connected our React components using react-redux. By implementing Redux, we achieved a clean and centralized approach to managing state, making it easier to scale and maintain our task list application. As your projects grow, you can further extend Redux to handle more complex state management needs and enjoy the benefits of a predictable and well-organized state management system.

Leave a Comment

Your email address will not be published. Required fields are marked *

Let's Get in Touch

Read our customer feedback

Please fill in the form below.


    To top