Search code examples
reactjsreduxreact-reduxredux-thunk

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?

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.