I have a fairly simple React component which renders two components within it: one is a big list and another is a modal. When a button within the list is clicked, the modal appears. This process is causing the list component to re-render, thus inducing the lag. There is a gap in my React knowledge as to why this is happening.
Here's the code:
const ExistingMargins = ({ margins }) => {
const [isModalOpen, setIsModalOpen] = useState(false);
const [marginBeingEdited, setMarginBeingEdited] = useState();
return (
<>
<TableRows
margins={margins}
onEditButtonClicked={(marginToEdit) => {
setMarginBeingEdited(marginToEdit);
setIsModalOpen(true);
}}
/>
<EditModal
isModalOpen={isModalOpen}
closeModal={() => setIsModalOpen(false)}
margin={marginBeingEdited}
/>
</>
);
};
const TableRows = ({ margins, onEditButtonClicked }) => {
return (
<table>
{margins.map(margin => (
<tr key={margin.Id}>
<td>{margin.Name}</td>
<td>
<button onClick={() => onEditButtonClicked(margin)}>Edit</button>
</td>
</tr>
))}
</table>
);
};
My understanding: is that React applies a unique key to the two components being rendered here (TableRows
and EditModal
) and that, whenever any state variable changes, the component re-renders and updates the shadow-DOM. React then compares the new and previous shadow-DOM to detect changes. Any changes get rendered in the actual-DOM. Since nothing in TableRows
is changing, no laggy updates to the actual-DOM happens.
This isn't the case. Here's what is actually happening:
- The user clicks the Edit button in the
TableRows
component - The
isModalOpen
andmarginBeingEdited
state variables in the parent component get updated - The entire
ExistingMargins
component re-renders - ...including the
TableRows
component, which causes lag
My understanding is that TableRows
shouldn't re-render on the actual-DOM because no state variables being passed to it have changed.
This is not happening. I can see in Chrome's React Profiler that there's a big, slow re-render of the table rows.
Why is this happening? Memoisation might fix it, but where is my understanding incorrect?