I'm picking up React and not sure if I'm doing this correctly. To preface the question I've read all about the React hooks; I understand them in isolation but am having trouble piecing them together in a real-life scenario.
Imagine I have a Parent component housing a list of Child components generated via a map
function on the parent:
<Parent>
{items.map(i => <Child item={i} />)}
</Parent>
And say the Child component is just a simple:
function Child({item}) {
return <div>{item}</div>
}
However the Child component needs to update its view, and be able to delete itself. My question is - should I call useState(item)
on the child so it internally has a copy of the item? In that case if I updated the item
the items
list in the parent wouldn't get updated right? To fix that I ended up having something that looks like:
<Parent>
{items.map(i =>
<Child
item={i}
updateItem={(index) => setItems( /* slice and concat items list at index */ )}
deleteItem={(index) => setItems( /* slice items list at index */ )}
/>)
}
</Parent>
And the Child
component simply invokes updateItem
and deleteItem
as appropriate, not using any React hooks.
My question here are as follows:
- should I have used
useState
in the child component? - should I have used
useCallback
on theupdateItem
/deleteItem
functions somehow? I tried using it but it didn't behave correctly (the correct item in the Parent got removed but the state in the remaining renderedChild
were showing values from the deletedChild
for example. - My understanding is that this would be very inefficient because an update on 1 child would force all other children to re-render despite them not having been updated.
If done most properly and efficiently, what should the code look like?
Thanks for the pointers.