I'm following the examples in https://mui.com/components/snackbars/ and I need to understand the differences between the function keyword and arrow keyword for this code below.
From what I've read online, the two ways to call functions is nearly identical. But I have a case below where this is not true.
This applies for all the functions in this example code.
Error when using function()
. No error when using the sample code which uses const myFunction() => {}
notation.
Sample code
const handleClick = () => {
setOpen(true);
};
Error case
function handleClick() {
setOpen(true);
};
Error message
Unhandled Runtime Error
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
Full code
import * as React from 'react';
import Button from '@mui/material/Button';
import Snackbar from '@mui/material/Snackbar';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
export default function SimpleSnackbar() {
const [open, setOpen] = React.useState(false);
const handleClick = () => {
setOpen(true);
};
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setOpen(false);
};
const action = (
<React.Fragment>
<Button color="secondary" size="small" onClick={handleClose}>
UNDO
</Button>
<IconButton
size="small"
aria-label="close"
color="inherit"
onClick={handleClose}
>
<CloseIcon fontSize="small" />
</IconButton>
</React.Fragment>
);
return (
<div>
<Button onClick={handleClick}>Open simple snackbar</Button>
<Snackbar
open={open}
autoHideDuration={6000}
onClose={handleClose}
message="Note archived"
action={action}
/>
</div>
);
}