Resetting Uncontrolled Inputs with key
You'll learn how to force uncontrolled inputs to reset to their default values by changing their key prop, making React treat them as entirely new components.
The Problem with Uncontrolled Inputs
As you learned in "When Default Props Don't Update," defaultValue and defaultChecked only work once — when the component first mounts. If you try changing these props later, nothing happens. The input remains stuck with whatever the user typed because React doesn't control it.
But what if you need to reset an uncontrolled form after submission, or clear it when switching between different data items?
The Key Trick
Here's the clever solution: change the input's key prop. When React sees a different key, it completely unmounts the old component and mounts a brand new one from scratch.
Think of it like replacing a physical notepad. You're not erasing the old notes — you're throwing away the entire notepad and getting a fresh one. The new notepad respects the defaultValue because, to React, it's a first-time setup.
function CommentForm({ postId }) {
const inputRef = useRef(null);
function handleSubmit(e) {
e.preventDefault();
// Submit the value...
// Form will reset automatically when postId changes
}
return (
<form onSubmit={handleSubmit}>
<input
key={postId} // Changes when postId changes
ref={inputRef}
type="text"
defaultValue=""
/>
<button>Submit</button>
</form>
);
}
When postId changes, React sees a new key, destroys the old input (and its user-typed value), and creates a fresh one with the empty defaultValue.
Key Takeaway: Force uncontrolled inputs to reset by changing their key prop — React will unmount the old component and mount a completely new one, respecting defaultValue or defaultChecked again.