Home > Mobile >  Why dispatch(actionObject) is called inside a anonymous arrow function?
Why dispatch(actionObject) is called inside a anonymous arrow function?

Time:10-04

Below is a simple ToDo-List Code by using useReducer().

I am trying to toggle the check box. Although Code is working

concept wise I am not able to understand why dispatch function is being called inside an anonymous arrow function ?

import initialTodos from "./Data";
import { useReducer } from "react";


const reducer = (state, action) => {
  switch (action.type) {
    case "COMPLETE":
      return state.map((todo) => {
        if (todo.id === action.id) {
          return { ...todo, complete: !todo.complete };
        } else {
          return todo;
        }
      });
    default:
      return state;
  }
};

export default function Todos() {
  const [todos, dispatch] = useReducer(reducer, initialTodos);

  return (
    <>
      {todos.map((todo) => (
        <div key={todo.id}>
          <label>
            <input
              type="checkbox"
              checked={todo.complete}
              onChange={() => dispatch({ type: "COMPLETE", id: todo.id });} // dispatch(actionObject);
            />
            {todo.title}
          </label>
        </div>
      ))}
    </>
  );
}

CodePudding user response:

In order to subscribe to any changes on the input, you need to provide the onChange event a callback function to call when the event occurs. One way of doing that is by passing an anonymous function.

CodePudding user response:

It's because, we don't have to call them, React calls it when the event is triggered.

just onChange = {dispatch()} would trigger dispatch immediately during rendering which you don't want ..

for more info read about events in docs

and the arrow function is just for less typing ...

  • Related