Redux Toolkit Introduction 2025
Redux Toolkit Introduction 2025
Redux Toolkit is the official, recommended way to write Redux logic. It makes working with Redux easier by reducing boilerplate code and simplifying common tasks like creating reducers, actions, and store setup.
Why Redux Toolkit?
- Less boilerplate
- Built-in best practices
- Comes with pre-built tools like
createSlice
, configureStore
- Improved developer experience
Installation
npm install @reduxjs/toolkit react-redux
Create a Redux Slice
A slice contains reducer logic and actions for a single feature of the app.
// features/counter/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
value: 0
};
export const counterSlice = createSlice({
name: 'counter',
initialState,
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;
Create Redux Store
// app/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';
export const store = configureStore({
reducer: {
counter: counterReducer
}
});
Provide Store to App
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';
ReactDOM.render(
,
document.getElementById('root')
);
Use Redux State and Dispatch
// Counter.js
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './features/counter/counterSlice';
function Counter() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
Count: {count}
);
}
export default Counter;
Conclusion
Redux Toolkit streamlines Redux usage by providing a simple and powerful API. It is the modern way to manage global state in React applications.