import "./styles.css"; import React from "react"; const getData = () => { return Array.from({ length: 50 }, (el, idx) => ({ value: Math.random(), label: `row ${idx + 1}`, })); }; export default function App() { const [data, setData] = React.useState(getData()); const handleUpdate = () => { setData((prev) => { return prev.map((row, i) => i === 0 ? { ...row, value: Math.random() } : row ); }); }; return ( <div> <h1>List App</h1> <Button onClick={handleUpdate}>update `row 1`</Button> {data.map((row) => { return <Row key={row.label} label={row.label} value={row.value} />; })} </div> ); }
sobes.tech AI
Answer from AI
The provided React component code creates a list of 50 items with value and label fields. When the button is clicked, only the first item in the list is updated, changing its value to a new random number.
The key point is that the setData function used to update the state creates a new array where only the first object is changed, and the rest remain the same. This is important for rendering optimization, as React compares objects by reference.
If the Row component is implemented with React.memo or shouldComponentUpdate, then only the first Row will re-render upon update, and the others will not, which improves performance.
Example of using React.memo for the Row component:
const Row = React.memo(({ label, value }) => {
console.log(`Render ${label}`);
return (
<div>
{label}: {value.toFixed(2)}
</div>
);
});
Thus, updating the state while preserving unchanged object references helps avoid unnecessary re-renders.