Blog>
Snippets

Configuring a Redux Store with Redux Toolkit in React-Redux 9

Demonstrate how to set up a Redux store using Redux Toolkit's configureStore in a React-Redux 9 application.
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './features/counter/counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});
This is the Redux store configuration using Redux Toolkit. It imports the configureStore function from the Redux Toolkit and the counterReducer from the counter feature slice. It then creates the store with the configureStore function, setting the reducer for the 'counter' feature.
import React from 'react';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';

const Root = () => (
  <Provider store={store}>
    <App />
  </Provider>
);

export default Root;
This code sets up the React-Redux Provider wrapping the App component. The Provider is imported from the react-redux library and the store is imported from the store configuration file. It provides the Redux store to the React App component.
import { createSlice } from '@reduxjs/toolkit';

export 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;
This code creates a Redux slice for a counter feature using createSlice from Redux Toolkit. It defines the name, initial state, and reducers for handling actions like increment, decrement, and incrementByAmount. The actions and reducer are then exported for use elsewhere in the app.