1

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>
  );
}

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
engineer-x
  • 2,173
  • 2
  • 12
  • 25
  • 1
    The handling of this is different in arrow functions compared to regular functions. In short, with arrow functions there are no binding of this. In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions the this keyword always represents the object that defined the arrow function Also in react code we call const this: handleClick = () => { setOpen(true); }; A function expression, when using this syntax, order is important as you cant call them before declare – Nacho Oct 18 '21 at 04:38

0 Answers0