Managing Complex State in Your React App using Redux

Table of contents

No heading

No headings in the article.

In a basic React app, state management can quickly become a headache as the app grows. The state updates in one component can trigger updates in another, leading to complex, hard-to-debug interactions.

Solution: Redux provides a centralized store to manage the state of your application. The state is updated using actions and reducers, and the updated state is available to all components that need it. This eliminates the need to pass props through multiple components and eliminates complex state updates.

In this post let us explore how we can use it in a react application. The app will be a simple expense-tracking application where users can add expenses and view a list of all the expenses they've added. The user will be able to add the name and amount of the expense, and the date it was incurred. Let's take a look at how we can use Redux in our expense tracking app.

First, we need to install the redux library.

npm install redux

Next, we need to set up the Redux store. The store is the central repository of all the state in our application.

import { createStore } from 'redux';

const initialState = {
  expenses: []
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_EXPENSE':
      return { ...state, expenses: [...state.expenses, action.payload] };
    default:
      return state;
  }
};

const store = createStore(reducer);

Next, we'll create a component for the form where the user can add expenses. This component will dispatch an action to add an expense to the Redux store when the form is submitted.

import React, { useState } from 'react';
import { useDispatch } from 'react-redux';

const AddExpenseForm = () => {
  const [name, setName] = useState('');
  const [amount, setAmount] = useState('');
  const [date, setDate] = useState('');
  const dispatch = useDispatch();

  const handleSubmit = e => {
    e.preventDefault();
    dispatch({
      type: 'ADD_EXPENSE',
      payload: { name, amount, date }
    });
    setName('');
    setAmount('');
    setDate('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Name"
        value={name}
        onChange={e => setName(e.target.value)}
      />
      <input
        type="text"
        placeholder="Amount"
        value={amount}
        onChange={e => setAmount(e.target.value)}
      />
      <input
        type="text"
        placeholder="Date"
        value={date}
        onChange={e => setDate(e.target.value)}
      />
      <button type="submit">Add Expense</button>
    </form>
  );
};

export default AddExpenseForm;

Finally, we'll create a component to display the list of expenses. This component will be connected to the Redux store and will receive the expenses from the store as props.

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

const ExpenseList = ({ expenses }) => {
  return(
    <div className="container">
      <ul>
        {expenses.map((expense, index) => (
          <li key={index} className="listContainer">
            <span className="expenseText">{expense.text}</span>
            <span className="expenseAmount">${expense.amount}</span>
          </li>
        ))}
      </ul>
    </div>
)};

const mapStateToProps = (state) => ({
  expenses: state.expenses
});

export default connect(mapStateToProps)(ExpenseList);
.container {
  padding: 20px;
  background-color: #f5f5f5;
}

.listContainer {
  display: flex;
  flex-direction: row;
  padding: 10px;
  border-bottom: 1px solid #cccccc;
  align-items: center;
}

.expenseText {
  font-size: 18px;
  margin-left: 10px;
  color: #444444;
}

.expenseAmount {
  font-size: 18px;
  margin-left: auto;
  color: #444444;
}

Benefits:

Let me summarise the benefits of using the Redux library so that you can opt to use it in your next react application.

  • Centralized state management

  • Predictable state updates

  • Easy debugging

  • Reusable code

  • Improved performance

In conclusion, Redux is a must-have tool for any React app that needs to manage complex state updates. It makes our app more scalable, maintainable, and predictable.

I hope this was helpful. Thank you! Happy learning.