InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
In ReactJS, why we used setState() function, why don’t we directly update the state like normal JavaScript?
In ReactJS, we use the setState() function to update the state because React needs to know when the state changes so it can re-render the UI. If we update the state directly (like normal JavaScript), React will not know about the change, and the UI will not update automatically.
Think of setState() as a way to tell React, "Hey, something changed! Please update the screen."
Directly changing the state is like changing something behind React’s back, React won’t notice, so the page might not show the latest data.
In short:
1: Use setState() so React can keep everything in sync and update the UI properly.
2: Don’t update state directly, or the UI might not work as expected.
Example:
Suppose you have a counter in React:
// WRONG way: Directly updating state
this.state.count = this.state.count + 1; // UI will NOT update
// CORRECT way: Using setState()
this.setState({ count: this.state.count + 1 }); // UI WILL update
Explanation
1: If you change count directly, React won’t know and won’t update the UI.
2: If you use setState(), React knows the state changed and will update the UI to show the new value.