Blog>
Snippets

Dispatching Actions from React Components with Redux Toolkit 2.0

Illustrate the correct pattern for dispatching actions from React components using the updated hooks API from Redux Toolkit 2.0.
import { createSlice } from '@reduxjs/toolkit';

// Define the initial state and the reducers
const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    incremented: state => {
      state.value += 1;
    },
    decremented: state => {
      state.value -= 1;
    }
  }
});

export const { incremented, decremented } = counterSlice.actions;
export default counterSlice.reducer;
This is a Redux Toolkit slice (counterSlice) which includes actions (incremented, decremented) and a reducer to handle these actions. This code defines how the state changes when those actions are dispatched.
import React from 'react';
import { useDispatch } from 'react-redux';
import { incremented, decremented } from './counterSlice';

// Example of a React component which dispatches actions
const CounterComponent = () => {
  const dispatch = useDispatch();

  return (
    <div>
      <button onClick={() => dispatch(incremented())}>+</button>
      <button onClick={() => dispatch(decremented())}>-</button>
    </div>
  );
};

export default CounterComponent;
This React component uses the useDispatch hook from Redux Toolkit to dispatch the incremented and decremented actions when the buttons are clicked.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Counter Example</title>
  <style>
    button {
      margin: 5px;
      padding: 10px;
    }
  </style>
</head>
<body>
  <div id="root"></div>
  <script src="bundle.js"></script>
</body>
</html>
This is the HTML document that includes a root div where the React application will be rendered, as well as the bundled JavaScript file (created by a tool like webpack or parcel) which includes the React application and Redux logic.