Dispatching Typed Actions with Redux Hooks
Show how to use typed actions with the useDispatch hook in Redux for more type-safe dispatch calls.
// Define Action Types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
// Define Action Creators
const increment = () => ({ type: INCREMENT });
const decrement = () => ({ type: DECREMENT });
This snippet defines the action types and corresponding action creators used to create actions that will be dispatched to the store.
// Importing useDispatch from react-redux
import { useDispatch } from 'react-redux';
// Importing action creators
import { increment, decrement } from './actionCreators';
function CounterComponent() {
// Typed useDispatch hook in use
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
This snippet showcases how to use the useDispatch hook from the react-redux package, along with the defined action creators to dispatch typed actions in a React functional component.