Redux toolkit CreateSlice Explain 2025
Redux Toolkit: CreateSlice Explain 2025
Redux Toolkit ka createSlice
function Redux state management ko simplify karta hai. Isme aap reducers aur actions ko ek hi jagah define kar sakte ho. Yeh Redux ke repetitive code ko kaafi kam kar deta hai.
📌 createSlice Syntax
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: {
count: 0
},
reducers: {
increment: (state) => {
state.count += 1;
},
decrement: (state) => {
state.count -= 1;
},
incrementByAmount: (state, action) => {
state.count += action.payload;
}
}
});
// Export actions
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
// Export reducer
export default counterSlice.reducer;
✅ Points to Remember:
- name: Slice ka naam hota hai
- initialState: Initial state define karta hai
- reducers: Functions hote hain jo state ko update karte hain
- Yeh actions automatically create hote hain
- Immer.js ka use karke aap directly state mutate kar sakte ho
📦 Usage in Component
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './counterSlice';
function Counter() {
const count = useSelector((state) => state.counter.count);
const dispatch = useDispatch();
return (
Count: {count}
);
}
👉 Yeh tha Redux Toolkit ka createSlice
. Ab aap Redux ka use simple aur fast bana sakte ho!