A "slice" is a collection of Redux reducer logic and actions for a single feature in your app, typically defined together in a single file
createSlice() function →A function that accepts an initial state, an object of reducer functions, and a "slice name", and automatically generates action creators and action types that correspond to the reducers and state.
Slice we can assume to be a part of store
Important Steps âž–
- Install react redux and redux toolkit
npm i @reduxjs/toolkit react-redux
- Create a file named
src/app/store.js
import {configureStore} from '@reduxjs/toolkit'
export const store = configureStore({
reducer:{},
})
- Wrap the components
import Provider from react-redux
import store from Store.jsx2
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import {Provider} from 'react-redux'
import {store} from './redux/Store.jsx'
ReactDOM.createRoot(document.getElementById('root')).render(
<Provider>
<App />
</Provider>,
)
- Creating Slice folders
- In redux context every feature is a slice like counting , commenting , like etc
- Now create Slice using createSlice ({})
for that import redux toolkit
also createSlice contains three keys namely initialState , name , reducers
after that export the action and reducers
\>counter > Index.jsx
**import {createSlice} from "@reduxjs/toolkit"
export const counterSlice = createSlice({
initialState : 0,
name : "counter",
reducers : {
increment : (state) => state+1,
decrement : (state) => state-1,
},
});
export const {increment , decrement} = counterSlice.actions;
export default counterSlice.reducer;**
- increment & decrement are the actions (what to do )
- Add Slice Reducers to the Store
import {configureStore} from '@reduxjs/toolkit'
import {counterSlice} from './slices/counter/Index'
export const store = configureStore({
reducer:{
counter : counterSlice,
},
})
- Using State Using useSelector and useDispatch hook
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { decrement, increment } from './counterSlice'
export function Counter() {
const count = useSelector((state) => state.counter.value)
const dispatch = useDispatch()
return (
<div>
<div>
<button
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
Increment
</button>
<span>{count}</span>
<button
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
Decrement
</button>
</div>
</div>
)
}
Â