In React, there are several ways to reset a component’s state, depending on how your component is structured (functional or class-based) and what exactly you want to reset.
Here are the main approaches 👇
🧩 1. Reset using a unique key prop
One of the simplest and most reliable methods.
If you give your component a different key value, React will unmount and remount it, causing all internal state to reset automatically.
function App() {
const [resetKey, setResetKey] = React.useState(0);
return (
<>
<MyForm key={resetKey} />
<button onClick={() => setResetKey(prev => prev + 1)}>Reset Form</button>
</>
);
}
function MyForm() {
const [name, setName] = React.useState("");
return (
<div>
<input value={name} onChange={e => setName(e.target.value)} />
<p>{name}</p>
</div>
);
}
👉 Changing resetKey remounts <MyForm />, clearing its state.
⚙️ 2. Reset using a state setter
If you just need to reset part of the state, you can call the state setter with the initial value.
function Counter() {
const [count, setCount] = React.useState(0);
const reset = () => setCount(0);
return (
<>
<p>{count}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
<button onClick={reset}>Reset</button>
</>
);
}
🪄 3. Use a custom “initial state” reference
If the state is complex, store the initial value separately and reuse it when resetting.
function UserProfile() {
const initialState = { name: "", age: "" };
const [form, setForm] = React.useState(initialState);
const resetForm = () => setForm(initialState);
}
🧱 4. For class components
You can directly reset state to its initial value using this.setState().
class Counter extends React.Component {
state = { count: 0 };
reset = () => this.setState({ count: 0 });
render() {
return (
<>
<p>{this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>+</button>
<button onClick={this.reset}>Reset</button>
</>
);
}
}
✅ Summary
| Method | When to Use |
|---|---|
Changing key prop |
Reset the entire component (simple & clean) |
| Using state setter | Reset specific states |
| Using stored initial state | Reset complex state objects |
this.setState (class) |
For class components |