Logo

dev-resources.site

for different kinds of informations.

State Management with Redux Toolkit: A Complete Guide

Published at
12/21/2024
Categories
tutorial
beginners
programming
redux
Author
sudhanshudevelopers
Author
19 person written this
sudhanshudevelopers
open
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! ๐Ÿš€

redux Article's
30 articles in total
Favicon
Redux Middleware เฆธเฆฎเงเฆชเฆฐเงเฆ•เง‡ เฆฌเฆฟเฆธเงเฆคเฆพเฆฐเฆฟเฆค เฆ†เฆฒเง‹เฆšเฆจเฆพ
Favicon
Comprehensive Redux Toolkit Notes for React Developers
Favicon
๐Ÿš€ Learning Through Experience: A Tale of NgRx Effects
Favicon
Why Use Redux in React? Complete Guide in Bangla
Favicon
State Management in React 2025: Exploring Modern Solutions
Favicon
[Boost]
Favicon
TypeScript + React Redux: Pro Tips for Type-Safe and Scalable Apps
Favicon
State Management in React: Redux vs. Context API vs. Recoil
Favicon
Redux com React
Favicon
Manual Setup (Custom Webpack/Babel configuration) with react (i am not able running it )
Favicon
TanStack query or RTK query.
Favicon
๐Ÿš€ React Best Practices for Scalable Frontends: Part 2 โ€“ State Management
Favicon
Redux Toolkit - createAsyncThunk()
Favicon
Bootcamping 02: Named exports and default exports - does it really matter?
Favicon
State Management with Redux Toolkit: A Complete Guide
Favicon
Boost Your Application's Performance with Redux RTK Query ๐Ÿš€
Favicon
Mastering State Machines with XState in React
Favicon
Mastering Redux Basics: A Complete Guide to State Management in React
Favicon
Mastering Redux Toolkit: Simplify State Management in Your React App
Favicon
Redux Made Simple: Managing State Like a Pro
Favicon
I have working on product customization
Favicon
Context, Redux or Composition?
Favicon
Learn Redux Toolkit - React (TypeScript)
Favicon
Por que eu nรฃo uso bibliotecas de gerenciamento de estado no React
Favicon
The Role of State Management in React: A Guide to Redux, Context API, and More
Favicon
Creating Theme Systems in React with SCSS and Redux
Favicon
Managing Data with Redux: Storing Content and IDs in Slices
Favicon
๐Ÿš€ Creating a Feature-Rich Redux Store with Redux Toolkit and TypeScript
Favicon
Redux vs Zustand: A Comprehensive Comparison
Favicon
Advanced Redux

Featured ones: