I’m in a situation where I want to dispatch an event in Redux. I’m noticing that defining const
in Javascript is a little bit confusing. When I’m trying to add a parameter directly to the useAppDispatch
function, the linter marks an error.
import { PlusCircleIcon } from "@heroicons/react/20/solid";
import React from "react";
import { useAppDispatch } from "../../store/hooks";
const OptionsPanelAddAction = ():JSX.Element => {
const handleOnClick = (e: React.MouseEvent<HTMLButtonElement>):void => {
e.preventDefault();
useAppDispatch({type: "ADD_CLICKED"}); ---> Expected 0 arguments, but got 1
}
return (
<div className="bg-white m-4 p-2 drop-shadow-sm flex justify-center">
<div>
<a><PlusCircleIcon className="h-6 w-6" /></a>
</div>
</div>
)
}
export default OptionsPanelAddAction;
But when I put the dispatch
function in a const I’m able to add an parameter:
import { PlusCircleIcon } from "@heroicons/react/20/solid";
import React from "react";
import { useAppDispatch } from "../../store/hooks";
const OptionsPanelAddAction = ():JSX.Element => {
const dispatch = useAppDispatch();
const handleOnClick = (e: React.MouseEvent<HTMLButtonElement>):void => {
e.preventDefault();
dispatch({type: "ADD_CLICKED"}); ---> No Error!
}
return (
<div className="bg-white m-4 p-2 drop-shadow-sm flex justify-center">
<div>
<a><PlusCircleIcon className="h-6 w-6" /></a>
</div>
</div>
)
}
export default OptionsPanelAddAction;
Can somebody explain this to me?
2
Answers
useAppDispatch
is a hook which returns a reference to the dispatch function from the Redux store. here is the docyou have to call the hook and then you can use the reference like this:
useAppDispatch
is a React hook that must be called on its own first prior to returning thedispatch
function. TheuseAppDispatch
function does not consume any arguments. The action object is passed to thedispatch
function, not the hook.Doesn’t work
Does work
While you could try something like
useAppDispatch()({type: "ADD_CLICKED"});
I wouldn’t recommend this at all as it is not a common use pattern and likely hurts readability/maintainability and may even break the Rules of Hooks given where you might be trying to call it.