🔥 What is React State?
In React, state is a built-in object that allows components to store and manage dynamic
data — data that changes over time or in response to user interaction.
🧠 Why is State Important?
● It determines what gets rendered on the screen.
● Whenever the state changes, React re-renders the component to reflect those changes
in the UI.
● It's what makes your app interactive.
🧩 State in Functional Components: useState Hook
React uses the useState() hook to manage state in functional components.
✅ Syntax:
const [stateVariable, setStateFunction] = useState(initialValue);
🧪 Example:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // count is 0 initially
const increase = () => setCount(count + 1);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={increase}>Click Me</button>
</div>
);
}
🔁 How State Works
● useState(0) initializes count to 0.
● When setCount(count + 1) is called, React:
○ Updates the count value.
○ Triggers a re-render of the component.
○ Shows the updated count on screen.
📌 Key Concepts
1. State is Local
● Each component has its own state.
● One component’s state is not shared unless you lift it up.
2. State is Immutable
● Don’t mutate the state directly (e.g., count = count + 1 ❌).
● Always use the setter function (setCount(...) ✅).
3. State Updates are Asynchronous
setCount(count + 1);
console.log(count); // might not log the updated value
🧃 Multiple States Example
function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
return (
<form>
<input onChange={(e) => setName(e.target.value)} value={name} />
<input onChange={(e) => setEmail(e.target.value)} value={email}
/>
<p>Hello {name}, your email is {email}</p>
</form>
);
}
✅ Best Practices
✅ Do This ❌ Avoid This
Use useState() for state Using plain variables
Use the updater function Mutating state directly
Keep state minimal Storing derived/computed values
Use functional updates Using outdated state references
📌 Functional Update Example
setCount(prev => prev + 1); // Safe when updating based on previous
state
🔄 Controlled vs Uncontrolled Inputs
Controlled:
Input value comes from state.
<input value={name} onChange={e => setName(e.target.value)} />
Uncontrolled:
Input value is managed by the DOM.
<input defaultValue="Sabid" />
💥 Common Pitfalls
1. Not using the setter function (setState) correctly.
2. Expecting state to update immediately.
3. Storing derived values in state unnecessarily.
4. Mutating arrays or objects directly.
🎯 Summary
Concept Description
useState() Hook to create and update state
Triggers re-render When state changes, React updates UI
State is async Logs or checks right after may be outdated
Immutable Always treat state as read-only
Controlled components Inputs bound to state via value and onChange