Redux toolkit

🧠 What is Redux Toolkit?

Redux Toolkit is the official, recommended way to use Redux — a tool that helps you manage global state in React apps.

Component State (Local State)

Belongs to one specific component. 

It’s used when only that component needs to know or control that data.

Example:

Imagine a light switch component in a room. The switch ON/OFF is tracked inside that component only — no other part of the house (app) needs to know about it.

function LightSwitch() { 

const [isOn, setIsOn] = useState(false); 

return <button onClick={() => setIsOn(!isOn)}>{isOn ? 'ON' : 'OFF'}</button>; 

}

Global State

This is shared state — data that multiple components need to access or update. It’s stored in a central place and can be used across the app. Example:
Imagine an app with a theme toggle (dark/light mode) that affects the whole app — not just one component.
If you stored this in just one component, others wouldn’t know when it changes. So, you use global state to manage it.

🧱 Why Redux Toolkit?

Old Redux:

Had a lot of boilerplate (repeated code)

Was hard to set up and maintain

Redux Toolkit:

✅ Less code

✅ Built-in tools to make life easier

✅ Encourages good practices

✅ Works great with TypeScript

File Structure of redux

Redux store will be outside of the app file. Here we create redux folder, inside that folder we create reduxSlices folder. Here contains all slices we create. For nextjs project, we create seperate Provider component where we import provider of redux and wrap children prop with it. And also import store we created in store.js

"use client";
import React from "react";
import { Provider } from "react-redux";
import store from "./store";

const Providers = ({ children }) => {
  return <Provider store={store}>{children}</Provider>;
};

export default Providers;

And use this component in layout.js of app component because it is the root/parent file.

import Providers from "./redux/Providers";
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased`}
      >
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

🔧 Basic Concepts in Redux Toolkit

1. Slice

A slice is like a section of your notebook for one part of your state (e.g., user info, cart items, theme).

It includes:

  • Name

  • Initial state

  • Reducers (functions to change the state)

  • Actions (labels for those changes)

// counterSlice.js
import { createSlice } from "@reduxjs/toolkit";
const counterSlice = createSlice({
  name: "counter",
  initialState: {
    value: 0,
    name: "bishal",
  },
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByValue: (state, action) => {
      state.value += Number(action.payload);
    },
  },
});
export const { increment, decrement, incrementByValue } = counterSlice.actions;
export default counterSlice.reducer;



2. Store

The store is the main state container — it combines all slices.

import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "./reduxSlices/counterSlice";
export default configureStore({
  reducer: {
    counter: counterSlice,
  },
});

3. Using in Components

"use client";
import {
  increment,
  decrement,
  incrementByValue,
} from "@/redux/reduxSlices/counterSlice";
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";

const page = () => {
  const { value } = useSelector((state) => state.counter);
  const dispatch = useDispatch();
  const [inputValue, setInputValue] = useState(0);
  return (
    <>
      <div className="w-1/3 border-1">
        <div>{value}</div>
        <input
          className="border-1"
          type="number"
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button
          className="p-2 bg-gray-300 m-2"
          onClick={() => dispatch(increment())}
        >
          +
        </button>
        <button
          className="p-2 bg-gray-300 m-2"
          onClick={() => dispatch(decrement())}
        >
          -
        </button>
        <button
          className="p-2 bg-gray-300 m-2"
          onClick={() => dispatch(incrementByValue(inputValue))}
        >
          IncByValue
        </button>
      </div>
    </>
  );
};

export default page;

Work Flow of Redux toolkit



function and hooks used

Concept Purpose
createSlice     Create state + actions + reducers easily
configureStore     Set up Redux store with less config
useSelector     Read data from the store
useDispatch     Send actions to update the state

Comments

Popular posts from this blog

Array Advance

HTML – a must-know for building responsive and dynamic layouts.