Chapter 5React Tutorial~1 min read
State with useState
State — Component ची Memory
State म्हणजे component चा changeable data. Counter, form input, loading status, toggle — हे सगळे state आहेत. State बदलली की React आपोआप UI re-render करतो. useState hook वापरून state manage करतात.
Marathi Analogy
State म्हणजे whiteboard वरचे notes सारखे. Notes बदलले की board आपोआप update होतो — manually erase-rewrite नको. useState म्हणजे React ला सांगतो: "हा data बदलला तर UI बदलव!"
useState — Counter example
jsx
import { useState } from 'react';
function Counter() {
// [currentValue, setterFunction] = useState(initialValue)
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
function decrement() {
setCount(count - 1);
}
function reset() {
setCount(0);
}
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
}State चे Multiple Examples
Toggle, string, object state
jsx
import { useState } from 'react';
function Examples() {
// Boolean toggle
const [isVisible, setIsVisible] = useState(false);
// String state
const [name, setName] = useState("");
// Object state
const [user, setUser] = useState({ name: "", age: 0 });
return (
<div>
{/* Toggle */}
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? "लपवा" : "दाखवा"}
</button>
{isVisible && <p>आता दिसतोय! 👋</p>}
{/* String */}
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="नाव टाका"
/>
<p>नमस्कार, {name}!</p>
{/* Object — spread operator वापरा */}
<input
value={user.name}
onChange={(e) => setUser({ ...user, name: e.target.value })}
/>
</div>
);
}Safe State Updates — Updater Function
prev state pattern
jsx
// ✅ Safe — prev state वापरा जेव्हा नवी value जुन्यावर depend असेल
function increment() {
setCount(prev => prev + 1);
}
// ❌ Risky — rapid clicks वर stale state येऊ शकते
function increment() {
setCount(count + 1);
}📌
State update asynchronous असते — setCount(5) केल्यावर लगेच count === 5 नसते. Next render मध्ये update होतो. म्हणून console.log(count) ताबडतोब केले तर जुनी value दिसते.
✅ Key Points — लक्षात ठेवा
- ▸const [val, setVal] = useState(initial) — hook syntax
- ▸State बदलली → React re-renders component
- ▸setVal(newValue) — state update करणे
- ▸setVal(prev => prev + 1) — safe updater pattern
- ▸Props = बाहेरून येतो, State = component चा स्वतःचा
0/12 chapters पूर्ण