Blog>
Snippets

Dispatching actions with useDispatch hook

Use the useDispatch hook from react-redux to dispatch actions in a functional component.
// actions.js
// Define your action creators
export const incrementCounter = () => {
  return {
    type: 'INCREMENT'
  };
};

export const decrementCounter = () => {
  return {
    type: 'DECREMENT'
  };
};
This file contains the action creators for incrementing and decrementing a counter. These action creators return plain action objects that have a 'type' property describing the action.
// CounterComponent.js
import React from 'react';
import { useDispatch } from 'react-redux';
import { incrementCounter, decrementCounter } from './actions';

const CounterComponent = () => {
  // Use `useDispatch` to get a reference to the dispatch function
  const dispatch = useDispatch();

  return (
    <div>
      <button onClick={() => dispatch(incrementCounter())}>Increment</button>
      <button onClick={() => dispatch(decrementCounter())}>Decrement</button>
    </div>
  );
};

export default CounterComponent;
This is a functional React component that uses the `useDispatch` hook from `react-redux` to dispatch increment and decrement actions. A user can interact with the buttons to increment or decrement the counter.
/* style.css */
button {
  margin: 5px;
  padding: 10px;
  font-size: 16px;
}

div {
  text-align: center;
  margin-top: 20px;
}
This is a simple CSS file that styles the buttons and div container in the CounterComponent.