2 answers
A state can be updated on the component directly or indirectly.
codelikepro
· 19 Aug 2022
Report
Was this answer helpful?
Thanks for the feedback.
Sign up free to save answers and ask your own doubts
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?
Thanks for the feedback.
Sign up free to save answers and ask your own doubts
Your answer
Log in or create a free account to answer this question.