Skip to content
doubtly

2 answers

Update state with the setter function from useState (function components) or with this.setState() (class components), never by changing the state variable directly.

Function component:

const [count, setCount] = useState(0);

setCount(count + 1);            // set a new value
setCount(prev => prev + 1);     // based on previous value

Class component:

this.setState({ count: this.state.count + 1 });
this.setState(prev => ({ count: prev.count + 1 }));

Calling the setter tells React that the state changed, so it re-renders the component. Writing this.state.count = 5 or count = 5 does not trigger a re-render. Since updates may be batched, use the function form (prev => ...) when the new value depends on the old one. For objects and arrays, create a new copy, e.g. setUser({ ...user, name: "Asha" }).

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.