Blog>
Snippets

Integrating Redux v5.0.0 with React Hooks

Show how to use React Hooks, such as useDispatch and useSelector, within a functional component in a project that has been updated to Redux v5.0.0.
// Import necessary hooks and functions
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { incrementCounter, decrementCounter } from './actions';

// A functional component using React Hooks with Redux
function CounterComponent() {
  // Access dispatch function
  const dispatch = useDispatch();

  // Get the counter value from the Redux state
  const counter = useSelector(state => state.counter);

  return (
    <div>
      <h1>Counter: {counter}</h1>
      // Dispatch actions on button click
      <button onClick={() => dispatch(incrementCounter())}>Increment</button>
      <button onClick={() => dispatch(decrementCounter())}>Decrement</button>
    </div>
  );
}

export default CounterComponent;
This code defines a functional React component called 'CounterComponent' which interacts with Redux state using hooks. The 'useDispatch' hook fetches the 'dispatch' function to dispatch actions to the Redux store, and 'useSelector' accesses the counter value from Redux state. Two buttons are rendered, each dispatching either an increment or decrement action, updating the state accordingly.