Blog>
Snippets

Utilizing New Redux Hooks for State Access

Showcase how to use the newly introduced hooks in Redux v5.0.1 for accessing and dispatching state within functional components.
import { useSelector, useDispatch } from 'react-redux';
import { increment } from './counterSlice';

// Functional component using Redux hooks
function CounterComponent() {
  // Access the Redux state using the useSelector hook
  const count = useSelector((state) => state.counter.value);

  // Get the dispatch function with the useDispatch hook
  const dispatch = useDispatch();

  // Event handler to dispatch an action
  const handleIncrement = () => {
    // Dispatch an action to increment the counter
    dispatch(increment());
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
}
This code snippet shows a functional component named CounterComponent. It uses the useSelector hook to access the current value of the counter from the Redux state and the useDispatch hook to get the dispatch function. The handleIncrement function is an event handler that dispatches the increment action when the button is clicked, which should update the counter state in the store.