Steps to Setup Redux-toolkit

First of all install redux-toolkit and react-redux
npm install @reduxjs/toolkit
npm install react-redux
Create the folder store
inside this folder create the index.js
file. after that make the slice
inside store
folder. inside slice
create your first slice
I have create the auth
slice.

index.js
import the
configureStore
formreduxjs/toolkit
now create the variable it might be different but I have created a “store” after “configureStore” → function which receive the object inside object it accept combine reducer in which can import all your slice’s
import { configureStore } from "@reduxjs/toolkit";
export const store = configureStore({
reducer: {
},
});
slice → auth.js
import the createSlice
after that createinitialState
the create your first slice. createSlice()
accept object in which require 3 keys
- Name of the slice ( this is for just redux )
- initialState
- All the reducer
reducer accepts an object of actions that have a key and function. The arrow function has two arguments “state” and “action”
export all the actions and then export the reducer
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
token : "initial token"
}
export const auth = createSlice({
name: "authRedux",
initialState,
reducers: {
setToken: (state , action) => {
state.token = action.payload
}
}
})
export const { setToken } = auth.actions
export default auth.reducer
After creating this slice import this slice. In `store → index.js`
import { configureStore } from "@reduxjs/toolkit";
import auth from "./slice/auth";
export const store = configureStore({
reducer: {
// first key is used in your all component to access this state and
// the secound one is alies of your import
auth: auth,
},
});
Now just wrap your <App/> in the provider and pass them store
to this provider
import { Provider } from "react-redux";
import { store } from "./store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
All Set, now we can just dispatch to update the value of our slice state. Dispatch is new to fire the action to update the value of the state.
import { setToken } from '../../../../store/slice/auth';
import { useSelector , useDispatch } from "react-redux";
const Home = () => {
const dispatch = useDispatch()
// output "initial Token"
dispatch(setToken("new Token"))
const Updated_Token = useSelector( state => state.auth.token)
// output "new Token"
}
export default Home;