React State β Explained in Detail
Subject: React
π§© What is State in React?
In React, state is an object that stores dynamic data for a component. When the state changes, React automatically re-renders the component to reflect the new data in the UI.
Think of state as the brain of your component β it remembers information over time and reacts to user input or events.
π Props vs State
| Props | State | 
|---|---|
| Passed from parent to child | Stored inside a component | 
| Read-only | Mutable (can change over time) | 
| Makes components reusable | Makes components interactive | 
β Using State in Functional Components
React uses a special Hook called useState() to manage state in functional components.
π§ Syntax:
state: the current valuesetState: function used to update the valueinitialValue: initial value (number, string, array, object, etc.)
π§ͺ Example: Counter App
π§Ύ Output:
β Using State in Class Components (Legacy)
π§ Why is State Important?
- Enables interactive components
 - Makes UI dynamic and responsive
 - Triggers automatic re-rendering on update
 
π Updating State Correctly
β Wrong:
β Right:
If new state depends on old state:
π§° Multiple State Variables
Or use an object:
π§ Best Practices
| Tip | Why? | 
|---|---|
| Use separate states for unrelated values | Improves clarity and avoids bugs | 
| Never modify state directly | React wonβt detect changes otherwise | 
| Use functional updates when needed | Avoid stale values | 
| Keep state minimal | Store only whatβs necessary | 
π Summary
| Concept | Description | 
|---|---|
| State | Data that determines component behavior | 
| useState Hook | Declares state in functional components | 
| setState | Updates state and re-renders component | 
| Class State | Uses this.state and this.setState() | 
π Final Words
State makes components dynamic.
It's a core concept for building interactive UIs.
Managed differently in functional and class components.
Advertisement Slot 1
Advertisement Slot 2