What is the difference between an onClick function which returns a callBack and the callBack directly put in the onClick?

Viewed 318

I want to create a react component which makes expansions panel like this https://material-ui.com/components/expansion-panels/ and I'm using a materialUI library.

    import React from "react";
    import { makeStyles } from "@material-ui/core/styles";
    import ExpansionPanel from "@material-ui/core/ExpansionPanel";
    import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails";
    import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary";
    import Typography from "@material-ui/core/Typography";
    import ExpandMoreIcon from "@material-ui/icons/ExpandMore";

    export default function ControlledExpansionPanels() {
      [...]
      const [expanded, setExpanded] = React.useState(false);

      const handleChange = panel => (event, isExpanded) => {
        setExpanded(isExpanded ? panel : false);
      };

      return (
        <>
          <ExpansionPanel
            expanded={expanded === "panel1"}
            onChange={handleChange("panel1")}
          >
            [...]
          </ExpansionPanel>
          <ExpansionPanel
            expanded={expanded === "panel2"}
            onChange={handleChange("panel2")}
          >
            [...]
          </ExpansionPanel>
        </>
      );
    }

Their component uses an onChange props which executes the function handleChange of the component to return a callBack function.

What is the difference with this method :

   [...]
      const handleChange = (event, isExpanded, panel) => {
        setExpanded(isExpanded ? panel : false);
      };

      return (
        <>
          <ExpansionPanel
            expanded={expanded === "panel1"}
            onChange={(event, isExpanded) => handleChange(event, isExpended, "panel1")}
          >
            [...]

I was wondering what was the difference between running a function that returns a callBack or putting the callBack directly into the onChange? I get the impression that it's a question of optimization with the number of anonymous function declared but, from my understanding, this code declares an anonymous function by executing handleChange, so a callBack is created for each onChange.

I would like to know when and why I should use each solution. Thank you in advance for your clarification.

1 Answers

You are correct it has to do with the number of anonymous functions declared.
It is slightly less efficient to do it the way they are doing with their handleChange as it declares an additional anonymous function but the difference is so small that the primary motivating factor is probably just to make the code readable and to look nice.

They must have decided that the code block to be executed onChange was too big to put right there and they wanted to wrap it in another function to keep the code organized.

Related