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?
CodePudding user response:
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.
CodePudding user response:
i think this little article could help answering your question https://dev.to/maddevs/a-bit-about-event-delegation-in-react-4jeo