4

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>
  );
}
1
  • 3
    Nothing wrong with that. The docs are full of examples just like this. Commented Dec 14, 2020 at 7:41

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.