Re-rendering of React components
Simplified re-rendering looks like this:
1. First, React creates "snapshots" of elements before and after the changes.
2. Then, it attempts to identify elements that were already on the page to reuse them instead of recreating them:
- If there is a key attribute, React assumes that elements with the same keys are identical before and after the changes.
- If the 'key' attribute is absent, it uses the default adjacent element indexes as keys.
3. Then React:
- Removes elements that were present before but absent after (unmounts them).
- Creates from scratch elements that were not present before (mounts them).
- Updates elements present before and still exist after (re-renders them).
Thus, keys play a crucial role in the re-rendering of a component. Incorrectly specified keys can lead to errors.
Index as a Key
Many automatically use the index as a key. Let's see what happens if we do that:
When removing an element from the list, you may notice that the correct item is removed, but the counters behave unexpectedly. This happens because changing the order of elements changes the indexes, and React cannot correctly match the elements.
Level up Frontend skills and advance your career
• Wide range of learning tracks for beginners and experienced developers
• Study at your own pace with your personal study plan
• Focus on practice and real-world experience