Course contentsShow
← React
Lesson 470 of 2,39613. Controlled ComponentsFree lesson

Benefits: Resetting Inputs Programmatically

Clearing or populating inputs becomes setState calls, no direct DOM manipulation needed.

Benefits: Resetting Inputs Programmatically

What you'll learn: How controlled components let you clear or populate form inputs with simple state updates—no DOM manipulation required.

The Old Way vs The React Way

In vanilla JavaScript, clearing an input meant finding the DOM element and directly setting its .value property. With controlled components, you simply update your state variable. Since the input's value is bound to state, React automatically reflects the change in the DOM.

Think of it like a thermostat display—you don't manually change what's shown on the screen. You adjust the temperature setting, and the display updates automatically.

How It Works

When your input's value comes from state and you call setState, React's update flow kicks in:

  1. You call setState with a new value (like an empty string)
  2. React re-renders the component
  3. The input receives the new value prop
  4. React updates the DOM to match
const [name, setName] = useState('');

// Clearing is just a state update
const handleClear = () => {
  setName(''); // Input becomes empty automatically
};

// Populating works the same way
const handlePrefill = () => {
  setName('John Doe'); // Input shows 'John Doe' automatically
};

return (
  <div>
    <input value={name} onChange={(e) => setName(e.target.value)} />
    <button onClick={handleClear}>Clear</button>
    <button onClick={handlePrefill}>Prefill</button>
  </div>
);

Why This Matters

This pattern is incredibly powerful for form resets after submission, "Edit" buttons that populate existing data, or clearing multiple fields at once by resetting your state object. No need to store references to DOM elements or manually coordinate updates.

Key Takeaway: With controlled components, resetting or populating inputs is just setState—the single source of truth pattern means React handles the DOM updates for you automatically.