I'm curious to what's a more performant way of handling list logic. For example...
The Item component
export default function Item({data}) => {
return <div>
<h1>{data.name}
<button> Do Something </button>
</div>
}
The List component
export default function List({list}) => {
return <div>
{list.map(item) => <Item data={item} />}
</div>
}
The Main component
export default function Main() {
return <div>
<List list={someList} />
</div>
}
If i want to do something with the button in the Item component is it better to place the logic inside the Item component like this:
export default function Item({data}) => {
const handleDoSomething = () => {
logic goes here
}
return <div>
<h1>{data.name}
<button onClick={() => handleDoSomething()}> Do Something </button>
</div>
}
Or should i propagate back the event to the List component and handle it there like this:
export default function Item({data, handleButtonClick}) => {
return <div>
<h1>{data.name}
<button onClick={() => handleButtonClick()}> Do Something </button>
</div>
}
export default function Main() {
const handleDoSomething = () => {
logic goes here
}
return <div>
<List list={someList} handleButtonClick={() => handleDoSomething()} />
</div>
}
What's the better to do this ? I want a better performance.
I guess that propagating back the event to the List component is better because the handler function will only be declared once, instead of once for every button that you render.
And btw, if you won't pass any custom argument to your handler function, you don't need to create an arrow function, you can just do:
<button onClick={handleButtonClick}> Do Something </button>