React development
June 28

Komponent hayotiy sikli (Lifecycle)

🔧 Komponent hayotiy sikli (Lifecycle) nima?

React’da har bir komponent uchta asosiy bosqichdan o‘tadi:

  1. Mount (yaratiladi va ekranga chiqadi) 🐣
  2. Update (props yoki state o‘zgarsa, yangilanadi) 🔁
  3. Unmount (ekrandan olib tashlanadi) ☠️
Buni odam hayoti kabi tasavvur qiling: tug‘iladi → o‘zgaradi → yo‘q bo‘ladi.

🧠 React’da lifecycle bilan qanday ishlaymiz?

Agar siz funksional komponent (function component) ishlatayotgan bo‘lsangiz, React sizga bu ishlar uchun useEffect() nomli maxsus hook beradi.

🔍 useEffect() — bu funksional komponentlar uchun lifecycle vositasi

Basic syntax:

useEffect(() => { // Bu kod har safar komponent render bo‘lgach ishlaydi }, []);

📦 useEffect() ichida nimalar qilish mumkin?

  • API’dan ma’lumot olib kelish
  • Timer yoki interval o‘rnatish
  • Ulanish (masalan: WebSocket)
  • State yoki props o‘zgarganda reaksiya qilish
  • Komponent o‘chirilganda kontentni tozalash

⚙️ useEffect hayotiy sikl misoli

useEffect(() => {
console.log("🔵 Component mounted (loaded)");

return () => {
console.log("🔴 Component unmounted (removed)");
};
}, []);

  • useEffect() ichidagi kod komponent render bo‘lgandan keyin ishlaydi
  • return ichidagi funksiya esa komponent ekrandan olib tashlanganda (unmount) ishlaydi

🔄 State o‘zgarganda ishlash (update bosqichi)

useEffect(() => { console.log("🟡 State yoki props o‘zgardi!"); }, [count]); // faqat 'count' o‘zgarganda ishlaydi

✅ Umumlashtirish:

useEffect(() => { console.log("🔵 Component mounted (loaded)");

return () => { console.log("🔴 Component unmounted (removed)"); }; }, []); // dependency array, empty array

useEffect ning qavslari yopilishidan oldin dependency array ni ko'rsatib ketish kerak. Aks holda component har render bo'lganida useEffect ishlab ketadi.