useState — Xusuusta Qaybta
Haddii props ay yihiin macluumaadka laga helo dibadda, state waa xusuusta gudaha ah ee qaybta. Marka state beddesho, React si otomaatig ah ayuu u dib-u-sawiraa (re-renders) qaybta.
Import-ka iyo Isticmaalka Asaasiga ah
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Tiradu waa: {count}</p>
<button onClick={() => setCount(count + 1)}>
Kordhee
</button>
</div>
);
}
useState waxay soo celisaa array leh laba shay:
- Qiimaha hadda jira (
count) - Function beddelida (
setCount)
Xeerka Xukuma State-ka
Marnaba si toos ah u beddelin state-ka
// ❌ Khalad
count = count + 1;
// ✅ Sax — isticmaal function-ka beddelida
setCount(count + 1);
React wuxuu xidhaa qaabkiisa dib-u-sawiridda (rendering) adigoo isticmaalaya function-ka beddelida. Haddii aad si toos ah u beddesho, UI-gu ma cusboonaanayso.
State-ku waa gaar
Qaybaha kala duwan waxay leeyihiin state gooni ah:
function App() {
return (
<div>
<Counter /> {/* count = 0 */}
<Counter /> {/* count = 0 — waa mid kale! */}
</div>
);
}
State oo ah Shay (Object)
function Foom() {
const [xog, setXog] = useState({
magac: '',
email: '',
xirfad: 'frontend',
});
function beddelMagac(e) {
setXog({
...xog, // ka hay waxyaabaha kale oo dhan
magac: e.target.value, // kaliya tan beddel
});
}
return (
<form>
<input
value={xog.magac}
onChange={beddelMagac}
placeholder="Magacaaga"
/>
<p>Ku soo dhowow, {xog.magac || 'martida'}!</p>
</form>
);
}
Xusuusnow
...xog— taas waxay nuqulisaa properties-ka jira oo dhan. Haddaan samayn, qiimayaashii kale ee state-ku way lumaan doonaan.
State oo ah Liis (Array)
function Liiska() {
const [sheyga, setSheyga] = useState([]);
const [gelinta, setGelinta] = useState('');
function ku_dar() {
if (!gelinta.trim()) return;
setSheyga([...sheyga, gelinta]); // nuqul oo kudar cusub
setGelinta('');
}
function tirtir(index) {
setSheyga(sheyga.filter((_, i) => i !== index));
}
return (
<div>
<div style={{ display: 'flex', gap: '8px' }}>
<input
value={gelinta}
onChange={e => setGelinta(e.target.value)}
onKeyDown={e => e.key === 'Enter' && ku_dar()}
placeholder="Ku dar shey..."
/>
<button onClick={ku_dar}>Kudar</button>
</div>
<ul>
{sheyga.map((shey, i) => (
<li key={i}>
{shey}
<button onClick={() => tirtir(i)}>✕</button>
</li>
))}
</ul>
</div>
);
}
Marka la isticmaalo Tusaha Hore (Previous State)
Marka state cusub uu ku xidnaado state hore, isticmaal functional update:
// ❌ Laga yaabaa inay khalad noqoto marka dhowr beddelid ay is-xigaan
setCount(count + 1);
// ✅ Habboon goorta oo dhan
setCount(prev => prev + 1);
Xirfad Dhaqameed
App To-Do List
Dhis app fudud oo to-do list ah adigoo isticmaalaya useState. In la darsan karo sheyga, in la dhammaystiro, iyo in la tirtiro.
Maxaa xiga?
Casharka xiga waxaan ku eegaynaa useEffect — sida aad ku samayso waxqabadyo marka qaybtu soo baxdo ama marka state beddesho.