Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Where to put useDispatch and bindActionCreators in a project?

My question is this, where do I put the methods mentioned above? Because in each component in which I want to use the Redux store, I need to basically repeat the mantra of,

import { useSelector, useDispatch } from "react-redux";
import { bindActionCreators } from "redux";
import * as actions from "../../redux/actions";

and then, for example,

const dispatch = useDispatch();
const { fetchStats } = bindActionCreators(actions, dispatch);

I’ve seen that some people make like a containers folder?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Also, what’s Your file structure? Where do you guys put the actions? How do you export them? All in one file or what? In bigger projects it’s not really efficient.

As always, thanks in advance!

>Solution :

The answer is, don’t.

bindActionCreators was really only ever used internally by the React-Redux connect function and not generally used by app code.

Today, with the React-Redux hooks API, we recommend just manually writing:

const dispatch = useDispatch();
const handleClick = () => dispatch(someActionCreator())

That way it’s more explicit what’s actually going on in the component.

Yes, that does require importing the hooks into the component. That’s both intentional and necessary to use them, like any other function.

We recommend against trying to separate out "container components", especially if you’re using the hooks API.

As for logic, you should be using a "feature folder" file structure using Redux Toolkit to create one "slice" file per feature containing the logic.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading