Blog>
Snippets

Replacing bindActionCreators with useDispatch

Demonstrate the process of replacing `bindActionCreators` with the `useDispatch` hook in a React component.
import { useDispatch } from 'react-redux';
import { increment, decrement } from './counterActions';

function CounterComponent() {
  // Using useDispatch hook to get the dispatch function
  const dispatch = useDispatch();

  // Dispatching actions directly using the dispatch function
  const incrementCounter = () => dispatch(increment());
  const decrementCounter = () => dispatch(decrement());

  return (
    <div>
      <button onClick={incrementCounter}>+</button>
      <span>/* counter value here */</span>
      <button onClick={decrementCounter}>-</button>
    </div>
  );
}

export default CounterComponent;
This code defines a CounterComponent. Instead of using bindActionCreators to bind action creators, it uses the useDispatch hook from 'react-redux' to create functions incrementCounter and decrementCounter that dispatch the increment and decrement actions, respectively, when called. These functions are then used as onClick handlers for the '+' and '-' buttons.