Sub topic 2
Reset State with a Key, Not an Effect
Assume you know function components, JSX, props, useState, useEffect, dependency arrays, and that state or prop changes cause re-renders.
Resetting state with a key
React preserves state while it renders the same component identity. A key changes that identity. When the key changes, React removes the old component and creates a new one with initial state.
Use this when all local state belongs to a particular item or user:
import { useState } from 'react';
export default function ProfilePage({ userId }) {
return <Profile userId={userId} key={userId} />;
}
function Profile({ userId }) {
const [comment, setComment] = useState('');
return (
<textarea
value={comment}
onChange={event => setComment(event.target.value)}
placeholder={`Comment on user ${userId}`}
/>
);
}Without the key, changing userId would preserve the existing comment. An Effect that calls setComment('') after userId changes adds an extra render and briefly keeps stale state.
Adjusting some state when a prop changes
A key resets all local state. Sometimes you need to preserve most state while adjusting one value. Prefer deriving the value during render when possible. If the state must change, a guarded render-time update can handle the transition:
function List({ items }) {
const [previousItems, setPreviousItems] = useState(items);
const [selectedId, setSelectedId] = useState(null);
if (items !== previousItems) {
setPreviousItems(items);
setSelectedId(null);
}
return (
<button onClick={() => setSelectedId(items[0]?.id ?? null)}>
Selected: {selectedId ?? 'none'}
</button>
);
}The condition is essential. Without it, each render would schedule another update.
Put user-triggered logic in event handlers
Logic caused by a click, submit, or selection belongs in that event handler. It does not need an Effect to observe state afterward.
function Form({ post }) {
const [name, setName] = useState('');
function handleSubmit(event) {
event.preventDefault();
post('/api/register', { name });
}
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={event => setName(event.target.value)} />
<button type="submit">Register</button>
</form>
);
}An Effect is for synchronization with an external system, not for replaying an action after rendering.
Exercise
A profile shows the previous user's draft after userId changes. Which pattern should you try first?
Show answer
Render the profile with key={userId} so React creates fresh state for each user.