Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I have one useDispatch per component?

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

like image 558
user3808307 Avatar asked Jan 30 '26 06:01

user3808307


1 Answers

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.

like image 138
Brian Thompson Avatar answered Feb 01 '26 18:02

Brian Thompson