Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
State preservation is React's ability to maintain component state between renders. When a component re-renders, React preserves its state values unless explicitly reset. This is fundamental to how React applications maintain user interactions and data.
State values persist across re-renders automatically.
State resets when component identity changes.
React resets state when it considers a component to be a different instance. This happens in specific scenarios that change the component's identity in React's virtual DOM.
When a component is removed from the DOM and later re-added
When the key prop value changes, React creates a new component instance
When components are rendered conditionally with different logic
Interactive demo showing when state is preserved vs reset
import React from 'react';
import { createRoot } from 'react-dom/client';
function App() {
const [showCounter, setShowCounter] = React.useState(true);
const [counterKey, setCounterKey] = React.useState(0);
const toggleCounter = () => {
setShowCounter(!showCounter);
};
const resetCounter = () => {
setCounterKey(prev => prev + 1);
};
return (
<div className="app">
<h1>🔄 State Preservation Demo</h1>
<p className="description">
See how React handles state preservation and reset
</p>
<div className="controls">
<button onClick={toggleCounter} className="btn btn-primary">
{showCounter ? '🙈 Hide Counter' : '👁️ Show Counter'}
</button>
<button onClick={resetCounter} className="btn btn-danger">
🔄 Reset Counter (Change Key)
</button>
</div>
<div className="demo-area">
{showCounter && (
<Counter key={counterKey} />
)}
</div>
<div className="info-panel">
<h3>📊 Current State</h3>
<div className="state-info">
<p><strong>Counter Visible:</strong> {showCounter ? 'Yes' : 'No'}</p>
<p><strong>Counter Key:</strong> {counterKey}</p>
<p><strong>State Status:</strong> {showCounter ? 'Preserved' : 'Hidden'}</p>
</div>
</div>
</div>
);
}
function Counter() {
const [count, setCount] = React.useState(0);
const [name, setName] = React.useState('User');
React.useEffect(() => {
console.log('Counter component mounted/updated');
});
return (
<div className="counter-card">
<h3>🎯 Counter Component</h3>
<p className="component-id">Component Instance</p>
<div className="counter-display">
<div className="count-value">{count}</div>
<p className="count-label">Current Count</p>
</div>
<div className="input-section">
<label>Name:</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
className="input-field"
/>
</div>
<div className="button-group">
<button onClick={() => setCount(count + 1)} className="btn btn-success">
➕ Increment
</button>
<button onClick={() => setCount(count - 1)} className="btn btn-warning">
➖ Decrement
</button>
<button onClick={() => setCount(0)} className="btn btn-secondary">
🔄 Reset Count
</button>
</div>
<div className="state-display">
<h4>📝 Current State</h4>
<p><strong>Count:</strong> {count}</p>
<p><strong>Name:</strong> {name}</p>
</div>
</div>
);
}
const root = createRoot(document.getElementById('root'));
root.render(React.createElement(App));Loading preview...
Multi-step form with state preservation and reset capabilities
import React from 'react';
import { createRoot } from 'react-dom/client';
function App() {
const [currentStep, setCurrentStep] = React.useState(1);
const [formKey, setFormKey] = React.useState(0);
const nextStep = () => {
if (currentStep < 3) {
setCurrentStep(currentStep + 1);
}
};
const prevStep = () => {
if (currentStep > 1) {
setCurrentStep(currentStep - 1);
}
};
const resetForm = () => {
setFormKey(prev => prev + 1);
setCurrentStep(1);
};
return (
<div className="app">
<h1>📝 Form State Management</h1>
<p className="description">
Navigate between steps and see how state is preserved or reset
</p>
<div className="step-indicator">
<div className={'step ' + (currentStep >= 1 ? 'active' : '')}>
<span className="step-number">1</span>
<span className="step-label">Personal Info</span>
</div>
<div className={'step ' + (currentStep >= 2 ? 'active' : '')}>
<span className="step-number">2</span>
<span className="step-label">Contact</span>
</div>
<div className={'step ' + (currentStep >= 3 ? 'active' : '')}>
<span className="step-number">3</span>
<span className="step-label">Review</span>
</div>
</div>
<div className="form-container">
<MultiStepForm
key={formKey}
currentStep={currentStep}
onNext={nextStep}
onPrev={prevStep}
onReset={resetForm}
/>
</div>
<div className="controls">
<button onClick={resetForm} className="btn btn-danger">
🔄 Reset Entire Form
</button>
</div>
</div>
);
}
function MultiStepForm({ currentStep, onNext, onPrev, onReset }) {
const [personalInfo, setPersonalInfo] = React.useState({
firstName: '',
lastName: '',
age: ''
});
const [contactInfo, setContactInfo] = React.useState({
email: '',
phone: '',
address: ''
});
const updatePersonalInfo = (field, value) => {
setPersonalInfo(prev => ({ ...prev, [field]: value }));
};
const updateContactInfo = (field, value) => {
setContactInfo(prev => ({ ...prev, [field]: value }));
};
return (
<div className="form-card">
{currentStep === 1 && (
<PersonalInfoStep
data={personalInfo}
onChange={updatePersonalInfo}
onNext={onNext}
/>
)}
{currentStep === 2 && (
<ContactStep
data={contactInfo}
onChange={updateContactInfo}
onNext={onNext}
onPrev={onPrev}
/>
)}
{currentStep === 3 && (
<ReviewStep
personalInfo={personalInfo}
contactInfo={contactInfo}
onPrev={onPrev}
onReset={onReset}
/>
)}
</div>
);
}
function PersonalInfoStep({ data, onChange, onNext }) {
const isFormValid = data.firstName && data.lastName && data.age;
return (
<div className="step-content">
<h3>👤 Personal Information</h3>
<p className="step-description">Tell us about yourself</p>
<div className="form-fields">
<div className="field-group">
<label>First Name</label>
<input
type="text"
value={data.firstName}
onChange={(e) => onChange('firstName', e.target.value)}
className="input-field"
placeholder="Enter your first name"
/>
</div>
<div className="field-group">
<label>Last Name</label>
<input
type="text"
value={data.lastName}
onChange={(e) => onChange('lastName', e.target.value)}
className="input-field"
placeholder="Enter your last name"
/>
</div>
<div className="field-group">
<label>Age</label>
<input
type="number"
value={data.age}
onChange={(e) => onChange('age', e.target.value)}
className="input-field"
placeholder="Enter your age"
/>
</div>
</div>
<div className="step-navigation">
<button
onClick={onNext}
disabled={!isFormValid}
className="btn btn-primary"
>
Next Step →
</button>
</div>
</div>
);
}
function ContactStep({ data, onChange, onNext, onPrev }) {
const isFormValid = data.email && data.phone;
return (
<div className="step-content">
<h3>📞 Contact Information</h3>
<p className="step-description">How can we reach you?</p>
<div className="form-fields">
<div className="field-group">
<label>Email</label>
<input
type="email"
value={data.email}
onChange={(e) => onChange('email', e.target.value)}
className="input-field"
placeholder="your@email.com"
/>
</div>
<div className="field-group">
<label>Phone</label>
<input
type="tel"
value={data.phone}
onChange={(e) => onChange('phone', e.target.value)}
className="input-field"
placeholder="+1 (555) 123-4567"
/>
</div>
<div className="field-group">
<label>Address</label>
<textarea
value={data.address}
onChange={(e) => onChange('address', e.target.value)}
className="input-field textarea"
placeholder="123 Main St, City, State"
rows={3}
/>
</div>
</div>
<div className="step-navigation">
<button onClick={onPrev} className="btn btn-secondary">
← Previous
</button>
<button
onClick={onNext}
disabled={!isFormValid}
className="btn btn-primary"
>
Next Step →
</button>
</div>
</div>
);
}
function ReviewStep({ personalInfo, contactInfo, onPrev, onReset }) {
const allFieldsFilled = personalInfo.firstName && personalInfo.lastName &&
personalInfo.age && contactInfo.email && contactInfo.phone;
return (
<div className="step-content">
<h3>📋 Review Your Information</h3>
<p className="step-description">Please review and confirm your details</p>
<div className="review-sections">
<div className="review-section">
<h4>👤 Personal Information</h4>
<div className="review-data">
<p><strong>Name:</strong> {personalInfo.firstName} {personalInfo.lastName}</p>
<p><strong>Age:</strong> {personalInfo.age}</p>
</div>
</div>
<div className="review-section">
<h4>📞 Contact Information</h4>
<div className="review-data">
<p><strong>Email:</strong> {contactInfo.email}</p>
<p><strong>Phone:</strong> {contactInfo.phone}</p>
{contactInfo.address && <p><strong>Address:</strong> {contactInfo.address}</p>}
</div>
</div>
</div>
<div className="step-navigation">
<button onClick={onPrev} className="btn btn-secondary">
← Previous
</button>
<button
onClick={onReset}
className="btn btn-success"
disabled={!allFieldsFilled}
>
✅ Submit & Reset
</button>
</div>
</div>
);
}
const root = createRoot(document.getElementById('root'));
root.render(React.createElement(App));Loading preview...
State preservation is React's default behavior. Understanding when and why state resets helps you build more predictable and efficient applications.