← React Beginner Questions - Set 6 Q59
React Beginner Questions - Set 6
Never by assignment. Both models give you a setter, and both merge or replace according to different rules.
// Function component
const [user, setUser] = useState({ name: 'Ana', city: 'Bogotá' });
setUser({ ...user, city: 'Medellín' }); // replace with a new object
setUser(prev => ({ ...prev, city: 'Cali' })); // safer under rapid updates
// Class component: setState merges at the top level
class Profile extends Component {
state = { name: 'Ana', city: 'Bogotá' };
move = () => this.setState({ city: 'Medellín' }); // name is preserved
}
// Both are asynchronous: read the value in the updater, not right after