简体   繁体   中英

is it ok to define a function inside a React stateless component?

Is it bad practice to define a function (like handleClick in the example below) inside a stateless component? I was told that you should avoid doing so, but I can't find anything in the documentation to confirm it. If the answer is "yes" then why is defining a function into a class instead any better?

function MiniPalette(props) {
  const {classes } = props;
  

  function handleClick() {
    history.push(`palette/${id}`);
  }

  return (
    <div className={classes.root} onClick={handleClick}>
      <div className={classes.colors}>{miniColorBoxes}</div>
      <h5 className={classes.title}>
        {paletteName}
        <span className={classes.emoji}>{emoji}</span>
      </h5>
    </div>
  );
}

It is generally a bad practice in javascript, not in React in particular. Basically if you declare a function inside a function, every time you call the parent function it will initialize the child function as well and it is a waste of resource. For details you can also check out this: https://code.tutsplus.com/tutorials/stop-nesting-functions-but-not-all-of-them--net-22315

Viet is correct in that it's a waste of resources. A good way to look at the component tree is that you want to process data at the top and near the bottom your focus is only in rendering the data. If for example you need a way to manipulate the data and update state, I would suggest passing hooks down or diverting to useContext(). This will also keep your code cleaner and you can eventually make use higher order components for like-functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM