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.