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?
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
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