Blog>
Snippets

Implementing Redux Toolkit with Redux v5.0.0

Provide an example showing how to set up and configure a store using Redux Toolkit in combination with the new features in Redux v5.0.0.
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './rootReducer'; // import your combined reducer

// Create a Redux store using Redux Toolkit's configureStore method
const store = configureStore({
  reducer: rootReducer
});

export default store;
This code snippet demonstrates how to import the configureStore function from Redux Toolkit and then use it to create a Redux store. The rootReducer is assumed to be a combined reducer imported from another file. The store is then exported for use throughout the application.
import { createSlice } from '@reduxjs/toolkit';

// Define a slice of the state and the corresponding reducer with the createSlice function
const exampleSlice = createSlice({
  name: 'example',
  initialState: { value: 0 },
  reducers: {
    increment: state => {
      state.value += 1;
    },
    decrement: state => {
      state.value -= 1;
    }
  }
});

export const { increment, decrement } = exampleSlice.actions;
export default exampleSlice.reducer;
This snippet demonstrates the process of creating a 'slice' using Redux Toolkit's createSlice function, which encapsulates the reducer logic and actions for a particular feature of the state. The actions to increment and decrement the value are exported along with the reducer itself.
import store from './store';
import { increment, decrement } from './exampleSlice';

// Dispatch actions to the store
store.dispatch(increment());
store.dispatch(decrement());
Here we're importing the store and action creators from their respective modules. Then we dispatch some actions to the store using the store.dispatch method to change the state. The increment and decrement actions will update the state according to the logic defined in the 'exampleSlice' reducers.