AceDevHub
Intermediate React Interview QuestionsIntermediateScenario

React · Question 51

Why can defining a component inside another component accidentally reset state?

Direct answer

A nested component definition creates a new component function on every parent render, so React can treat the child as a different component type and recreate its subtree.

Parent.jsx
function Parent() {
  const [count, setCount] = useState(0);

  // Avoid defining component types here.
  function Form() {
    const [text, setText] = useState("");
    return <input value={text} onChange={e => setText(e.target.value)} />;
  }

  return (
    <>
      <button onClick={() => setCount(c => c + 1)}>{count}</button>
      <Form />
    </>
  );
}

Move Form to module scope so its component type remains stable across Parent renders.