skip to Main Content

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


  1. useAppDispatch is a hook which returns a reference to the dispatch function from the Redux store. here is the doc

    you have to call the hook and then you can use the reference like this:

    const dispatch = useAppDispatch()
    dispatch({type: "ADD_CLICKED"});
    
    Login or Signup to reply.
  2. useAppDispatch is a React hook that must be called on its own first prior to returning the dispatch function. The useAppDispatch function does not consume any arguments. The action object is passed to the dispatch function, not the hook.

    Doesn’t work

    useAppDispatch({type: "ADD_CLICKED"});
    

    Does work

    const dispatch = useAppDispatch();
    
    ...
    
    dispatch({type: "ADD_CLICKED"});
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search