Join the discussion
Comments
Loading comments...
Cookie preferences
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Join the discussion
Loading comments...
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Wie die Key-Prop React ermöglicht, Listenelemente zu identifizieren und DOM-Mutationen zu minimieren.
Wenn React eine Liste von Elementen rendert, muss es wissen, welche Elemente sich zwischen Renderings geändert haben, hinzugefügt oder entfernt wurden. Ohne die key-Prop verwendet React positionsbasiertes Zuordnen — Element an Index 0 wird Element an Index 0 zugeordnet. Mit Keys kann React Elemente über Renderings hinweg nach stabiler Identität zuordnen, was effiziente Verschiebungen anstelle von Zerstören-und-Neuerstellen ermöglicht.
Wenn Ihre Liste neu rendert, hat React zwei Arrays von Kind-Elementen: die alten und die neuen. Es muss sie zuordnen, um zu entscheiden, was aktualisiert, eingefügt und gelöscht werden soll.
React ordnet Elemente nach ihrer Indexposition zu. Wenn die Liste [A, B, C] zu [B, A, C] wird (neu geordnet), sieht React, dass sich Position 0 von A zu B und Position 1 von B zu A geändert hat — was zwei Updates und möglichen Zustandsverlust verursacht.
React erstellt eine Zuordnung von Key zu Fiber. [A, B, C] wird zu [B, A, C] als 'key=b von Position 1 zu 0 verschoben, key=a von 1 zu 0 verschoben' gesehen. React verschiebt die vorhandenen DOM-Knoten — kein Zerstören/Erstellen-Zyklus.
React protokolliert 'Each child in a list should have a unique key prop', wenn es Listen ohne Keys erkennt. Dies ist eine Leistungswarnung — Ihre App funktioniert weiterhin, rendert aber weniger effizient.
Das Ändern des Keys einer Komponente teilt React mit: 'Dies ist eine völlig andere Instanz'. React hebt die alte Komponente auf (führt alle Bereinigungen aus) und mountet eine neue. Dies ist nützlich, um den Komponentenzustand absichtlich zurückzusetzen.
Ein Key, der ein Element über Renderings hinweg identifiziert — typischerweise eine Datenbank-ID oder ein Slug. Muss unter Geschwistern eindeutig sein.
Array-Index als Key zu verwenden ist nur für statische, nicht neu ordnende Listen sicher. Bei dynamischen Listen verursacht es Fehler, wenn Elemente neu geordnet werden.
Wenn React ein altes und neues Element nach Key zuordnet, verwendet es den vorhandenen DOM-Knoten wieder und aktualisiert nur geänderte Attribute.
Das absichtliche Ändern der key-Prop einer Komponente setzt sie zurück — nützlich zum Zurücksetzen des Formular-Zustands beim Wechsel zwischen Elementen.
1// ❌ Bad — index as key on dynamic list2{todos.map((todo, index) => (3 <TodoItem key={index} todo={todo} />4))}5// If you delete item at index 0, all items shift — React6// sees every item as 'changed' and re-renders all of them.78// ✅ Good — stable unique ID9{todos.map((todo) => (10 <TodoItem key={todo.id} todo={todo} />11))}12// Deleting one item: React only removes that one node.13// All others are matched by key and kept untouched.1415// 🔄 Intentional reset via key change16<UserProfile key={userId} userId={userId} />17// Changing userId resets all internal state — no need for18// a manual reset effect.
Keys sind Reacts Hinweis zum Zuordnen alter und neuer Listenelemente. Ein guter Key bedeutet, dass React DOM-Knoten wiederverwenden kann (schnell), den Komponentenzustand erhalten kann (korrekt) und minimale Updates auslöst (effizient). Ein schlechter Key (oder kein Key) bedeutet, dass React entweder viel mehr Arbeit als nötig leisten oder den Komponentenzustand unerwartet verlieren muss.
You have a form builder where users can add, remove, and reorder form fields via drag-and-drop. Each field has its own validation state and user input. After reordering, the input values appear in the wrong fields.
Using array index as key means when a user drags field 3 to position 1, React matches the component at position 1 (old field 1) with the new key=1 (field 3's new position). The old component instance retains field 1's input value but now renders field 3's label — a state/UI mismatch.
Assign each form field a stable UUID when created (e.g., `crypto.randomUUID()`). Use this as the key. Now drag-and-drop reordering just changes positions — React recognizes each component by its UUID and moves the DOM nodes without resetting any state.
Takeaway: For any list that supports add, remove, reorder, or filter operations, always use a stable unique ID as the key. Array index only works for truly static, never-reordered lists (like a static navigation menu).
A user profile edit form should reset to clean state whenever the selected user changes. You tried resetting state in useEffect but there's a flash of old data before the reset takes effect.
Setting state in useEffect happens AFTER render and paint. The sequence is: render (shows old user's data) → paint (user sees stale data) → useEffect fires (resets state) → re-render (shows new user's data). This causes a visible flash.
Add `key={userId}` to the form component. When userId changes, React sees a different key at the same position and unmounts the old instance entirely, creating a fresh one. No useEffect needed — the new instance starts with default initial state. Zero flash.
Takeaway: The `key` prop is not just for lists — it's a powerful tool to force React to destroy and recreate a component. Use it whenever you want a 'clean slate' without the complexity and timing issues of manually resetting state in useEffect.