Redux Toolkit in React
Prerequisite:
Basic React, Redux, React hooks.
React and Redux is believed to be the best combination for managing state in large-scale React applications. However, with time, the popularity of Redux has fallen due to;
Redux Tool Kit Purpose
Redux Tool Kit provides some options to configure the global store and create both actions and reducers more streamlined by abstracting the Redux API as much as possible. It was originally created to help address three common concerns about Redux:
Main features of Redux Tool Kit API?
Redux Toolkit includes these APIs:
Let's start with a simple example of the counter,
Redux Toolkit is available as a package on NPM for use with a module bundler or in a Node application:
Recommended by LinkedIn
Install it in your current react app.
# NPM
npm install @reduxjs/toolkitM
First, we will create a reducer file for it, name it counter.js
import { createSlice } from "@reduxjs/toolkit"
export 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;
}
}
});
//Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } =
counterSlice.actions;
export default counterSlice.reducer;
Now we have to create a global store, you can name it anything but for standardizing we will name it store.js.
import { configureStore } from "@reduxjs/toolkit"
import counterReducer from "./counter";
export default configureStore({
reducer: {
counter: counterReducer
}
});
Now we will import this store in our main index.js file so the global store is available in all files.
import ReactDOM from "react-dom"
import { Provider } from "react-redux";
import App from "./App";
import store from "./redux/store";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>,
rootElement
);
And now in our app component, we import this reducer and use redux to use this global store.
import React from "react"
import { useDispatch, useSelector } from "react-redux";
import { decrement, increment, incrementByAmount } from "./redux/counter";
export default function App() {
const { count } = useSelector((state) => state.counter);
const dispatch = useDispatch();
return (
<div className="App">
<h1> The count is: {count}</h1>
<button onClick={() => dispatch(increment())}>increment</button>
<button onClick={() => dispatch(decrement())}>decrement</button>
<button onClick={() => dispatch(incrementByAmount(33))}>
Increment by 33
</button>
</div>
);
};
For code reference, you can follow this codesandbox example.