Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to call React-Redux's useDispatch() multiple times in the same component?

I've seen people make action creators (functions that return an action object to avoid typos) like this:

// ReduxStuff.js

export const makeJuice = flavor => ({type: "MAKE_JUICE", load: flavor})

Now when a component needs to make juice, you would do this:

// MangoJuiceMaker.js

import { useDispatch } from "react-redux";
import { makeJuice } from "ReduxStuff";

const MangoJuiceMaker = () => {
    const dispatch = useDispatch();

    return <button onClick={dispatch(makeJuice("mango"))}>Make Mango Juice!</button>
}

The problem I see with this pattern is that every time a component needs to update the state, two imports must be done, one for useDispatch() and one for the action, so I came up with the following solution:

// ReduxStuff.js

import { useDispatch } from "react-redux";

const useMakeJuice = flavor => {
    const dispatch = useDispatch();
    return () => {
        dispatch({type: "MAKE_JUICE", load: flavor})
    }
}

Now when my component needs to update the state I just do one single import like this:

// MangoJuiceMaker.js

import { useMakeJuice } from "ReduxStuff";

const MangoJuiceMaker = () => {
    const makeJuice = useMakeJuice();

    return <button onClick={makeJuice("mango")}>Make Mango Juice!</button>
}

This custom hook works great actually. I haven't had any issues at all. But there's one thing grinding my gears. If the same component updates the store in multiple ways, then useDispatch() is called multiple times. Example:

// MangoJuiceAndBreadMaker.js

import { useMakeJuice, useMakeBread } from "ReduxStuff";

const MangoJuiceAndBreadMaker = () => {
    const makeJuice = useMakeJuice(); // This calls useDispatch()
    const makeBread = useMakeBread(); // This calls useDispatch() again

    return(
        <div>
            <button onClick={makeJuice("mango")}>Make Mango Juice!</button>
            <button onClick={makeBread()}>Make Bread!</button>
        </div>
    )
}

Even though this solution has worked ok so far, I feel like this is an anti-pattern and should be avoided. The fact that I don't see people using it in their code (I googled and googled and found not a single instance of this approach being used) makes me feel unsafe.

What are your thoughts about this?

like image 460
Pedro Rodriguez Avatar asked Sep 05 '25 02:09

Pedro Rodriguez


1 Answers

I don't believe there's anything wrong with this, useDispatch isn't some expensive operation or anything, it literally just gives that hook/component/whatever a reference to the dispatch function. Like importing the same component/script in different files, it's perfectly fine.

One point to note, based on react redux docs here, is that when creating callbacks that use dispatch, they should be memoized with useCallback

like image 60
Jayce444 Avatar answered Sep 08 '25 00:09

Jayce444