Utilizing Redux Hooks in Functional Components
Provide examples on how to replace connect() with new hooks like useSelector and useDispatch that are introduced in v5.0.0 for managing state in functional components.
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './actionCreators'; // Import your action creators
const CounterComponent = () => {
// Access state with useSelector
const count = useSelector(state => state.counter);
// Get the dispatch function with useDispatch
const dispatch = useDispatch();
return (
<div>
<h1>Count: {count}</h1>
// Dispatch actions with the dispatch function
<button onClick={() => dispatch(increment())}>Increase</button>
<button onClick={() => dispatch(decrement())}>Decrease</button>
</div>
);
};
export default CounterComponent;
This functional component uses the useSelector hook to access the 'counter' property from the Redux state and the useDispatch hook to dispatch 'increment' and 'decrement' actions. The component renders the current counter value and buttons for increasing and decreasing the count.