The foundation of any strong React application is state management. Redux has long been a reliable tool for component-to-component state management, particularly in intricate applications. But for beginners, putting it up could be difficult and verbose. Presenting Redux Toolkit (RTK), a more user-friendly, potent, and effective method of incorporating Redux into your React apps.
The fundamentals of utilizing Redux Toolkit with React and how it streamlines state management will be discussed in this article.
What is Redux Toolkit?
The official, suggested method for writing Redux logic is Redux Toolkit. It provides a simplified API and wraps Redux’s essential functionalities, which:
- Reduces boilerplate by offering best practices and shortcuts.
- Provides a “batteries included” setup with middleware, DevTools, and other configuration options.
- Immer’s default support for immutability enables programmers to create “mutative” code that is actually immutable.
Why Use Redux Toolkit?
- Simple Setup: Creating a store and slices is quicker, and the configuration is easier than with vanilla Redux.
- Optimized: RTK is designed with best practices in mind, like avoiding deeply nested switch statements in reducers.
- Reduced Boilerplate: Reduces the setup time and code needed to manage slices and actions, focusing more on the business logic.
Setting Up RTK in a React App
Let’s get started with a simple example to show you how to use RTK in a React project.
Step 1: Create a New React App
First, ensure you have a React project. If not, you can create one by running:
npx create-react-app my-app
cd my-app
Step 2: Install Redux Toolkit and React-Redux
Next, install the necessary dependencies:
npm install @reduxjs/toolkit react-redux
Step 3: Create a Slice
In RTK, a “slice” is a portion of your state that consists of actions, reducers, and the state. Let’s make a straightforward counter slice.
- In your
srcfolder, create a new file:counterSlice.js. - Define your slice in
counterSlice.js:
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { state.value += 1; },
decrement: (state) => { state.value -= 1; },
incrementByAmount: (state, action) => { state.value += action.payload; }
},
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
Step 4: Configure the Store
Next, configure your store. Create a store.js file in the src folder.
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
const store = configureStore({
reducer: {
counter: counterReducer,
},
});
export default store;
RTK configureStore automatically installs DevTools and middleware to facilitate debugging.
Step 5: Provide the Store to Your App
To make the store accessible throughout your app, wrap it in the Provider component and send it as a prop. Modify index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Step 6: Accessing State and Dispatching Actions
You may now use your components’ dispatch actions and state. Let’s make a basic counter component in Counter.js, for example.
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from './counterSlice';
function Counter() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
<button onClick={() => dispatch(incrementByAmount(5))}>
Increment by 5
</button>
</div>
);
}
export default Counter;
This is what’s taking place in Counter.js:
- The state (state.counter.value) is accessed by useSelector.
- useDispatch Sends out actions (such increments and decrements) to change the state.
Conclusion
RTK is an excellent option for React apps of any size since it makes Redux implementation easier. RTK makes it more simpler to set up slices, actions, and the store, allowing you to concentrate on the logic of your app rather than boilerplate. You should have no trouble managing state in a more effective and sustainable manner if you adhere to this approach.
Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency.