I am transitioning a react with redux project from class components to hooks.
To dispatch actions I am importing { useDispatch } from react-redux.
Then, in each functional component, I have
const dispatch = useDispatch();
And then
dispatch(someAction())
Is this the correct way to proceed or should the const dispatch = useDispatch() be abstracted to a separate file and reused all throughout?
Thank you
No, do it like you have it. Putting it in its own file won't add any value, it'd just be a custom hook that wraps another hook.
The react-redux hooks rely on context, so you'd still have to call the custom hook within each component or it won't have access to the context it needs. You wouldn't be able to just export dispatch and call it like dispatch(someAction()) after importing it.
You can check out the implementation of useDispatch here. You'll notice it eventually uses useReduxContext which is just a wrapper for useContext(ReactReduxContext). Which means the functional component that uses useDispatch must be a child of Provider which sets that context.
So calling useDispatch in an abstracted function would not work. And in order to get it to work, you would lose the value of abstracting it in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With