DEV Community

Cover image for Guide to Redux: A Robust State Management Library for JavaScript Applications
Abdullah
Abdullah

Posted on

Guide to Redux: A Robust State Management Library for JavaScript Applications

Redux is widely recognized as a robust state management library designed specifically for JavaScript applications, often utilized in tandem with the popular framework React. By offering a dependable state container, Redux establishes a solid foundation that greatly simplifies the task of handling and troubleshooting application states. This guide delves deeply into the fundamental components that comprise Redux, providing detailed explanations of each element and illustrating how they synergistically interoperate to streamline the overall functionality of the application. This in-depth exploration aims to elucidate the inner workings of Redux, empowering developers to grasp the intricacies of this state management tool and harness its capabilities effectively in their projects.

Table of Contents

  1. Introduction to Redux
  2. Setting Up Redux in a React Application
  3. Actions and Action Types
  4. Reducers and Slices
  5. Configuring the Store
  6. Connecting React Components
  7. Conclusion and References

1. Introduction to Redux

Redux follows a unidirectional data flow model and is based on three core principles:

  • Single source of truth: The state of your whole application is stored in an object tree within a single store. This centralization makes it easier to debug and track changes across your application.
  • State is read-only: The only way to change the state is to emit an action, an object describing what happened. This ensures that state mutations are predictable and traceable.
  • Changes are made with pure functions: To specify how the state tree is transformed by actions, you write pure reducers. Pure functions are predictable and testable, which simplifies debugging and unit testing.

2. Setting Up Redux in a React Application

First, install Redux and React-Redux:

npm install redux react-redux @reduxjs/toolkit
Enter fullscreen mode Exit fullscreen mode

This command installs the core Redux library, the React bindings for Redux, and the Redux Toolkit, which simplifies many common tasks like setting up the store and creating slices.

3. Actions and Action Types

Actions are payloads of information that send data from your application to your Redux store. Action types are constants that represent the action.

actionTypes.js

export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";
export const INCREMENT_BY_VALUE = "INCREMENT_BY_VALUE";
export const RESET = "RESET";

export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });
export const incrementByValue = (value) => ({
  type: INCREMENT_BY_VALUE,
  payload: value,
});
export const reset = () => ({ type: RESET });
Enter fullscreen mode Exit fullscreen mode

Defining actions and action types clearly helps maintain consistency and reduces errors in your application.

4. Reducers and Slices

Reducers specify how the application's state changes in response to actions sent to the store. Slices are a collection of Redux reducer logic and actions for a single feature of your app, created using Redux Toolkit's createSlice method.

counterSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = { number: 0 };

const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    increment: (state) => {
      state.number += 5;
    },
    decrement: (state) => {
      state.number = Math.max(0, state.number - 5);
    },
    incrementByValue: (state, action) => {
      state.number += action.payload;
    },
    reset: (state) => {
      state.number = 0;
    },
  },
});

export const { increment, decrement, incrementByValue, reset } = counterSlice.actions;

export default counterSlice.reducer;
Enter fullscreen mode Exit fullscreen mode

To combine multiple slices:

rootReducer.js

import { combineReducers } from "@reduxjs/toolkit";
import counterReducer from "../slices/counterSlice";

const rootReducer = combineReducers({
  counter: counterReducer,
});

export default rootReducer;
Enter fullscreen mode Exit fullscreen mode

5. Configuring the Store

The store is the object that brings actions and reducers together. It holds the application state, allows access to it via getState(), updates it via dispatch(action), and registers listeners via subscribe(listener).

store.js

import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "../reducers/rootReducer";

const store = configureStore({
  reducer: rootReducer,
});

export default store;
Enter fullscreen mode Exit fullscreen mode

6. Connecting React Components

To connect React components to the Redux store, use the Provider component from react-redux to pass the store down to your components, and use the useSelector and useDispatch hooks to access and manipulate the state.

App.js

import React from "react";
import { Provider } from "react-redux";
import store from "./redux/store/store";
import Counter from "./components/Counter";
import MusCo from "./MusCo redux logo.png";

function App() {
  return (
    <Provider store={store}>
      <div className="container mx-auto mt-24 text-center">
        <img src={MusCo} alt="logo" className="w-40 mx-auto mt-24 rounded-full" />
        <h1 className="container m-auto text-2xl font-semibold text-center text-violet-700">
          Practice Redux with <span className="font-extrabold text-violet-900">MusCo</span>
        </h1>
        <div className="relative inline-block mt-8 text-sm">
          <Counter />
          <h5 className="absolute bottom-0 right-0 mb-2 mr-2 font-semibold text-violet-700">
            <span className="italic font-normal">by</span> 
            <span className="font-semibold text-violet-900">Mus</span>tafa 
            <span className="font-semibold text-violet-900">Coskuncelebi</span>
          </h5>
        </div>
      </div>
    </Provider>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

CounterComponent.js


import { useDispatch, useSelector } from "react-redux";
import {
  decrement,
  increment,
  incrementByValue,
  reset,
} from "../slices/counterSlice";
import { useState, useEffect } from "react";

function Counter() {
  const [value, setValue] = useState("");
  const dispatch = useDispatch();
  const number = useSelector((state) => state.counter.number);

  useEffect(() => {
    const showcase = document.querySelector("#showcase");
    if (number < 5) {
      showcase.style.visibility = "visible";
    } else {
      showcase.style.visibility = "hidden";
    }
  }, [number]);

  return (
    <div className="container p-5 mx-auto mt-20 text-center bg-green-100 rounded-md shadow-md" style={{ width: "500px" }}>
      <h1 className="mb-3 text-3xl font-bold mt-7 text-violet-700">Counter</h1>
      <p className="text-5xl text-violet-900">{number}</p>
      <div className="flex mx-8 space-x-5" style={{ justifyContent: "space-around" }}>
        <button onClick={() => dispatch(increment())} className="w-40 h-10 p-2 mt-5 rounded-md outline-1 outline-violet-500 outline text-violet-900" style={{ backgroundColor: "#c2ff72" }}>
          Increment by 5
        </button>
        <button onClick={() => dispatch(decrement())} className="w-40 h-10 p-2 mt-5 rounded-md outline-1 outline-violet-500 outline text-violet-900" style={number < 5 ? { backgroundColor: "transparent" } : { backgroundColor: "#c2ff72" }} disabled={number < 5}>
          Decrement by 5
        </button>
      </div>
      <div className="flex mx-8 mt-5 space-x-3 mb-7" style={{ justifyContent: "space-around", alignItems: "center" }}>
        <div className="p-5 space-x-5 rounded-md outline outline-1 outline-violet-500">
          <input className="w-40 h-10 pl-2 rounded-md outline outline-1 outline-violet-500 text-violet-900" 
                 onChange={(e) => {
                   let newValue = e.target.value.trim();
                   if (newValue === "") {
                     newValue = "";
                     reset();
                   }
                   if (/^\d*$/.test(newValue)) {
                     setValue(newValue);
                   }
                 }} 
                 value={value} 
                 placeholder="Enter Value" />
          <button onClick={() => {
            dispatch(incrementByValue(Number(value)));
            setValue("");
          }} className="w-40 h-10 p-2 rounded-md outline-1 outline-violet-500 outline text-violet-900" style={{ backgroundColor: "#c2ff72" }}>
            Add this Value
          </button>
        </div>
      </div>
      <button onClick={() => {
        dispatch(reset());
        setValue("");
      }} className="w-20 h-10 p-2 text-white rounded-md outline-1 outline-violet-500

 outline mb-7 bg-violet-900">
        Reset
      </button>
      <h3 className="text-violet-400" id="showcase" style={{ visibility: "hidden", marginBottom: "100px" }}>
        Counter cannot be less than 0
      </h3>
    </div>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

7. Conclusion and References

Redux is a powerful library for managing state in your applications. By understanding actions, reducers, the store, and how to connect everything to your React components, you can create predictable and maintainable applications.

Key Points:

  • Actions: Define what should happen in your app.
  • Reducers: Specify how the state changes in response to actions.
  • Store: Holds the state and handles the actions.
  • Provider: Passes the store down to your React components.

For more information, check out the official Redux documentation:

By following this guide, you should have a solid understanding of Redux and be able to implement it in your own applications.

Top comments (0)