DEV Community

Cover image for State Management with Redux Toolkit: A Complete Guide
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

State Management with Redux Toolkit: A Complete Guide

Introduction
In modern web development, managing application state efficiently is crucial. Redux, a popular state management library for JavaScript applications, provides a reliable and predictable way to handle state. However, its setup can be complex, involving boilerplate code and multiple dependencies. Enter Redux Toolkitβ€”an official package from the Redux team that streamlines Redux development, reduces complexity, and boosts productivity. In this post, we'll explore Redux Toolkit, its features, and how to get started with it.

The Easy Way to Use Redux Toolkit in React πŸš€

Web Development Simplified

Web development evolves rapidly, introducing new libraries and tools to make developers' lives easier. Among these, ReactJS and Redux Toolkit stand out as powerful tools for building efficient, scalable, and maintainable applications.

What is Redux Toolkit?

ReactJS is a popular JavaScript library for building interactive user interfaces (UIs). It's widely adopted by companies like Facebook, Netflix, and PayPal for its ability to simplify the UI development process.

Key benefits of ReactJS:

  • Component-Based Architecture: Break UIs into reusable components.
  • Fast Rendering: Virtual DOM ensures speedy updates.
  • Rich Ecosystem: Integrates seamlessly with other tools like Redux.

Here's a recommended folder structure for your project using Redux Toolkit and React:

src/
β”œβ”€β”€ components/          # Reusable components
β”‚   β”œβ”€β”€ Page.js          # Main Page component
β”‚   └── Post.js          # Example Post component
β”œβ”€β”€ features/            # Redux slices (state logic)
β”‚   └── themeSlice.js    # Theme-related slice
β”œβ”€β”€ store/               # Redux store setup
β”‚   └── store.js         # Central Redux store
β”œβ”€β”€ App.js               # Root React component
β”œβ”€β”€ index.js             # Entry point with ReactDOM rendering
└── styles/              # Styles for the application
    └── main.css         # General styles

Enter fullscreen mode Exit fullscreen mode

Description of Each Folder
1.components/: Contains all reusable React components. Each component can have its own folder if it involves styles or tests.
Page.js: Example page that uses Redux state and actions.
Post.js: An example sub-component.

2.features/: Includes Redux slices for managing state logic.
themeSlice.js: Contains createSlicelogic for theme management.

3.store/: Centralized configuration for Redux.
store.js: Includes configureStore with slices combined.

4.styles/: For CSS files or other styling approaches.
main.css: Main stylesheet for the app.

5.App.js: Root application component that contains routes and layout.

6.index.js: Entry point for the React app, where the Provider wraps the App component to connect the Redux store.

How Redux Works?

Image description

Getting Started with Redux Toolkit πŸš€

Here’s a simple example to manage the theme of a React app using Redux Toolkit.

1.Install Dependencies:

npm install @reduxjs/toolkit react-redux

Enter fullscreen mode Exit fullscreen mode

2.Create a Redux Slice
In src/features/themeSlice.js:

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

const initialState = { value: { activeTheme: "light" } };

export const themeSlice = createSlice({
  name: "theme",
  initialState,
  reducers: {
    changeTheme: (state, action) => {
      state.value.activeTheme = action.payload;
    },
  },
});

export const { changeTheme } = themeSlice.actions;
export default themeSlice.reducer;

Enter fullscreen mode Exit fullscreen mode

3.Set Up the Redux Store
In src/store/store.js:

import { configureStore } from "@reduxjs/toolkit";
import themeReducer from "../features/themeSlice";

export const store = configureStore({
  reducer: {
    theme: themeReducer,
  },
});

Enter fullscreen mode Exit fullscreen mode

4.Provide the Store
In yourindex.js:

import { Provider } from "react-redux";
import { store } from "./store/store";
import App from "./App";

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

Enter fullscreen mode Exit fullscreen mode

5.Use Redux in Components
InPage.js:

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { changeTheme } from "../features/themeSlice";

const Page = () => {
  const theme = useSelector((state) => state.theme.value);
  const dispatch = useDispatch();

  const isDark = theme.activeTheme === "dark";

  const handleChangeTheme = () => {
    dispatch(changeTheme(isDark ? "light" : "dark"));
  };

  return (
    <div style={{ background: isDark ? "#333" : "#fff", color: isDark ? "#fff" : "#000" }}>
      <button onClick={handleChangeTheme}>
        Switch to {isDark ? "Light" : "Dark"} Theme
      </button>
      <p>Current theme: {theme.activeTheme}</p>
    </div>
  );
};

export default Page;

Enter fullscreen mode Exit fullscreen mode

Why Use Redux Toolkit? πŸ› οΈ
Redux Toolkit streamlines Redux development, offering:

  • Simplicity: Combine state, reducers, and actions in one createSlicecall.
  • Efficiency: Avoid manual immutability handling with Immer integration.
  • Flexibility: Built-in tools like RTK Query for data fetching.

Conclusion:
Redux Toolkit revolutionizes Redux state management, reducing boilerplate and complexity while improving productivity. Whether you're a beginner or an experienced developer, Redux Toolkit is a must-have for modern web development.

Start using Redux Toolkit today to experience the power of simplified state management!

References:

Image description

This guide provides a clear, beginner-friendly approach to using Redux Toolkit in React. Let us know your thoughts in the comments! πŸš€

Top comments (0)