I would have guessed that this question is a dupe, but I searched and I can't find it... Full source for this q is here: https://github.com/micahg/arraytest.
Using react, I'm mapping an array of objects (stored with useState) to a component for display. I'd like react to only render objects in the array with changed properties - but anything I've tried either renders every member or none. The (simplified) component:
const ContainerComponent = () => {
const [things, setThings] = useState<Thing[]>([]);
const change = () => {
const newThing: Thing = {...things[0], name: "Third"};
things.splice(0, 1);
const newThings = [...things, newThing];
setThings(newThings);
}
useEffect(() => {
const initialThings: Thing[] = [ { id: 1, name: "First" }, { id: 2, name: "Second"} ];
setThings(initialThings);
}, []);
return (
<div>
<div>Container</div>
<div>
{things.map(thing => <ContentComponent key={thing.id} thing={thing}/>)}
</div>
<button onClick={change}>Change</button>
</div>
);
}
I'm looking for the way to update the array so that react knows not to redraw the second element. What i notice in the react developer tools flamegraph is that the first ContentComponent rerenders because "Props changed" (makes sense) but the second rerenders because "The parent component rerendered".
So far the best I can do is just export default memo(ContentComponent); in ChildComponent to avoid executing the second ChildComponent code... but is there a way to get react to redrawing that second child entirely?
Thanks in advance,
things.splice(0, 1);always creating a new one - useState documentationconst newThings = [...[...things].slice(0, 1), newThing];