What is state in React?
In React, state is an object that stores dynamic, changeable data within a component.
When the state changes, React automatically re-renders the component to update the UI.
Think of state as a component’s private data storage that can change over time.
💡 Key Points About State
📍 Local to the Component → Each component has its own state.
🔄 Mutable → Updated using setState-like methods (in Hooks, we use useState).
⚡ Triggers Re-render → UI refreshes when state changes.
📤 Can be Passed Down → As props to child components.
✅ Functional Component Example (with useState)
1. import React, { useState } from "react";
2.
3. const Counter = () => {
4. const [count, setCount] = useState(0); // count = state variable
5.
6. return (
7. <div>
8. <h1>Count: {count}</h1>
9. <button onClick={() => setCount(count + 1)}>Increment</button>
10. </div>
11. );
12. };
13.
14. export default Counter;
🎤 Interview Q&A
❓ 1. How is state different from props in React?
Answer:
State → Local to the component, mutable, used for dynamic data.
Props → Passed from parent, immutable, used for customization.
❓ 2. Why should we avoid modifying state directly?
Answer:
Direct modification won’t trigger re-render.
React’s useState ensures predictable updates and UI refresh.
Wrong ❌:
count = 5; // No re-render
Right ✅:
setCount(5);
❓ 3. Can we use multiple state variables in a functional component?
Answer:
✅
Yes , by calling useState multiple times.
This keeps state values independent and easier to manage.
Example:
1. const [name, setName] = useState("PC");
2. const [age, setAge] = useState(25);