React Component Resets on Key Change

React Interview Question 🧠 Why Changing key RESETS Your Component (Hidden React Behavior)❓ “Why does this input lose its value?” function App() { const [id, setId] = useState(1); return ( <> <button onClick={() => setId(id + 1)}>Change</button> <Input key={id} /> </> ); } function Input() { const [text, setText] = useState(""); return <input onChange={e => setText(e.target.value)} />; } 😐 Most people think: ❌ Component just re-renders ❌ Reality: Component UNMOUNTS + REMOUNTS 🤯 Real Explanation (Interview-Ready): 1) key is component identity 2) Change in key ⇒ React treats it as a new component 3) Old component destroyed → state lost 4) New component created → fresh state 🔥 When this is ACTUALLY useful 1) Reset forms intentionally 2) Restart animations 3) Clear internal state safely 💬 Interview Gold Line: “Changing a key forces React to remount the component, not re-render it.” 📌 Save this — this question filters real React understanding #ReactJS #ReactInterview #JavaScript #FrontendDeveloper #WebDevelopment #AdvancedReact #InterviewPrep

To view or add a comment, sign in

Explore content categories