Blog>
Snippets

Updating connect to useSelector and useDispatch

Transition from using the `connect` HOC to using the `useSelector` and `useDispatch` hooks within functional components.
// 1. Import useSelector and useDispatch from 'react-redux'
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { incrementCounter } from './actions'; // replace with actual action creators

// 2. Functional component using useSelector and useDispatch
const CounterComponent = () => {
    // Replace 'state.counter' with the appropriate state slice
    const count = useSelector(state => state.counter);
    const dispatch = useDispatch();

    return (
        <div>
            <h1>Count: {count}</h1>
            <button onClick={() => dispatch(incrementCounter())}>Increment</button>
        </div>
    );
};

export default CounterComponent;
This code first imports the `useSelector` and `useDispatch` hooks from `react-redux`, and any necessary action creators. Inside the `CounterComponent`, the `useSelector` hook is used to access the `counter` value from the Redux store state. The `useDispatch` hook is used to create a `dispatch` function, which is then used to dispatch actions when clicking the button. The `incrementCounter` action creator would typically be a function imported from another file where Redux actions are defined.