Passing functions by reference is usually the way to go when you have arguments.
I was working on a webpage last sprint and I was wondering why my component kept firing it’s callback functions seemingly out of nowhere.
Consider the scenario:
type ComponentProps = {
handleChange: (value: boolean) => void;
}
const Component = ({handleChange}: ComponentProps) => {
return <Button onClick={handleChange(false)}/>
}
const Component = ({handleChange}: ComponentProps) => {
return <Button onClick={() => handleChange(false)}
}
I thought they did the same thing, but 1 is actually a bug.
handleChange(false) is called on render because the JSX interpreter interprets anything in {} when creating the virtual DOM. So, when React tries to figure out what value to assign to onClick, it executes and gets the return value of handleChange(false) (probably undefined if there’s no return).
Then, when we actually click the Button, the function isn’t called because onClick tries to run undefined().
2 is what’s known as an arrow function that is then passed by reference to the onClick prop which properly executes only when the Button is clicked.