Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which way of event handling is better for performance reasons in React?

To set one event handler on parent element?
#1:

const SomeComponent = () => {
  const [index, setIndex] = useState(0);
  const parentEventHandler = (event: React.MouseEvent) => {
    const divId = parseInt((event.target as HTMLElement).id);
    if (isNaN(divId)) return;
    setIndex(divId);
  };
  return (
    <div onClick={parentEventHandler}>
      <div id={'0'}></div>
      <div id={'1'}></div>
      <div id={'2'}></div>
      <div id={'3'}></div>
    </div>
  );
};

Or to set event handler for each child element?
#2:

const SomeComponent = () => {
  const [index, setIndex] = useState(0);
  return (
    <div>
      <div onClick={() => setIndex(0)}></div>
      <div onClick={() => setIndex(1)}></div>
      <div onClick={() => setIndex(2)}></div>
      <div onClick={() => setIndex(3)}></div>
    </div>
  );
};

Which way of handling should I choose for better performance in React? #1 or #2?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Its not important regardless. Some might say technically the number 1 example would be "quicker" because it it is not creating callback functions on each render for each item. This would be wrong since the contents of the handler in #1 like parseInt, the ID property access and isNan check would make actual interaction "slower".

But what you are talking about is nanoseconds. So the significantly decreased readability of that #1 example is what you really need to think about. It would be an extremely odd choice to bin the readability of your code for something which is far far less (several orders of magnitude) recognizable than a human beings perception.

Use option 2.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading