Implementing Typed Hooks with React-Redux 9.0
Exemplify the use of `useSelector` and `useDispatch` hooks with TypeScript enhancements in React-Redux 9.0.
// Define the state type
interface RootState {
counter: number;
}
// Selector hook with types
const selectCounter = (state: RootState) => state.counter;
// Component using useSelector and useDispatch with types
const CounterComponent: React.FC = () => {
// Typed useSelector hook usage
const counter = useSelector<RootState, number>(selectCounter);
// Typed useDispatch hook usage
const dispatch = useDispatch<Dispatch<AnyAction>>();
return (
<div>
<p>Counter: {counter}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
};
This code defines a RootState type to type the state within Redux store. It uses a typed selector to retrieve the counter state and typed useDispatch to dispatch actions in a functional React component.