React Hooks: useState ve useEffect Tam Rehber

React Hooks: useState ve useEffect Tam Rehber

React Hooks, fonksiyonel bileşenlerle state ve lifecycle yönetimini mümkün kılar.

useState

// (c) CodeMareFi - codemarefi.com.tr
import { useState } from 'react';
function Sayac() {
  const [sayi, setSayi] = useState(0);
  return (
    <div>
      <p>Sayı: {sayi}</p>
      <button onClick={() => setSayi(sayi + 1)}>Artır</button>
      <button onClick={() => setSayi(0)}>Sıfırla</button>
    </div>
  );
}

useEffect

// (c) CodeMareFi - codemarefi.com.tr
import { useState, useEffect } from 'react';
function kullanıcı({ id }) {
  const [kullanıcı, setKullanıcı] = useState(null);
  useEffect(() => {
    fetch('/api/users/' + id)
      .then(r => r.json())
      .then(data => setKullanıcı(data));
    return () => { /* temizlik */ };
  }, [id]); // id degisince tekrar calis
  if (!kullanıcı) return <p>yükleniyor...</p>;
  return <p>{kullanıcı.isim}</p>;
}
© CodeMareFi Bu içerik codemarefi.com.tr ye aittir.

0 Yorum

YORUM YAPMAK İÇİN SİSTEME SIZMANIZ GEREKİYOR

Lütfen yukarıdaki butonu kullanarak giriş yapın veya kimlik oluşturun.

Yorumlar yükleniyor...