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.
Key prop React ko list items identify karne aur DOM mutations minimize karne mein kaise help karta hai.
Jab React elements ki list render karta hai, usse pata hona chahiye ki renders ke beech kaunse items bade, add hue, ya remove hue. key prop ke bina, React position-based matching use karta hai â index 0 ka item index 0 ke item se map hota hai. Keys ke saath, React items ko renders ke across stable identity se match kar sakta hai, destroy-and-recreate ki jagah efficient moves enable karta hai.
Jab aapki list re-render hoti hai, React ke paas child elements ke do arrays hote hain: purane aur naye. Usse unhe match karna hota hai yeh decide karne ke liye ki kya update, insert, aur delete karna hai.
React elements ko unke index position se match karta hai. Agar list [A, B, C] se [B, A, C] (reordered) ban jaaye, React dekhta hai ki position 0 A se B mein badli aur position 1 B se A mein â do updates aur potential state loss cause karta hai.
React key se fiber ka ek map banata hai. [A, B, C] ka [B, A, C] banna 'key=b position 1 se 0 par gaya, key=a position 0 se 1 par gaya' ke roop mein dekha jaata hai. React existing DOM nodes move karta hai â koi destroy/create cycle nahi.
React 'Each child in a list should have a unique key prop' log karta hai jab woh keys ke bina lists detect karta hai. Yeh ek performance warning hai â aapki app phir bhi kaam karti hai lekin kam efficiently render hoti hai.
Ek component ki key change karna React ko batata hai 'yeh bilkul alag instance hai'. React purana component unmount karega (saari cleanups run karke) aur ek naya fresh mount karega. Yeh deliberately component state reset karne ke liye useful hai.
Ek key jo renders ke across ek item identify karti hai â typically ek database ID ya slug. Siblings mein unique honi chahiye.
Array index ko key ke roop mein use karna sirf static, non-reordering lists ke liye safe hai. Dynamic lists ke liye, items reorder hone par bugs cause karta hai.
Jab React ek purane aur naye element ko key se match karta hai, existing DOM node reuse karta hai aur sirf changed attributes update karta hai.
Kisi component ki key prop deliberately change karna usse reset karta hai â items ke beech switch karte waqt form state reset karne ke liye useful.
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 React ka hint hai purane aur naye list items match karne ke liye. Ek acchi key matlab React DOM nodes reuse kar sakta hai (fast), component state preserve kar sakta hai (correct), aur minimal updates trigger kar sakta hai (efficient). Ek buri key (ya koi key nahi) matlab React ya toh zaroorat se zyada mehnat karta hai ya unexpectedly component state kho deta hai.
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.