CodeBlanks Logo Icon CodeBlanks

useState

useState ile sayaç state'ini öğrenirsin.

useState nedir?

useState, React'in bir hook'udur. Bir bileşenin durum (state) tutmasını sağlar. Durum değiştiğinde bileşen yeniden render edilir ve ekran güncellenir.

Kullanımı: const [count, setCount] = useState(0);. Burada count mevcut değer, setCount ise onu değiştiren fonksiyondur. 0 başlangıç değeridir.

useState'i react paketinden içe aktarman gerekir: import { useState } from 'react';.

useState ile sayaç

Sayacı sabit 0 yerine useState ile tutacağız. Böylece değer değiştikçe ekran otomatik güncellenir.

İki değişiklik yapacağız: birincisi import { useState } from 'react'; satırını eklemek; ikincisi const [count, setCount] = useState(0); tanımını App bileşeni içine koymak.

Son olarak <Text>Sayaç: 0</Text> içindeki 0'ı {count} ile değiştireceğiz.

Uygulama useState ekle

Mevcut iskelete useState ekle. react'ten useState'i içe aktar. App bileşeni içinde const [count, setCount] = useState(0); tanımını yap. <Text> içinde Sayaç: {count} göster.

Başlangıç kodu

App.js
import { View, Text } from 'react-native';

export default function App() {
  return (
    <View>
      <Text>Sayaç: 0</Text>
    </View>
  );
}

Örnek çözüm

App.js
import { View, Text } from 'react-native';
import { useState } from 'react';

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <View>
      <Text>Sayaç: {count}</Text>
    </View>
  );
}

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 useState çağrısı

Soru
const [count, setCount] = ____(0);
Cevap
const [count, setCount] = useState(0);

Açıklama: useState(0) başlangıç değeri 0 olan durum oluşturur.

2 useState nasıl kullanılır?

  • const count = useState(0);
  • const [count] = useState;
  • const [count, setCount] = useState(0); Doğru cevap
  • const setCount = useState(0);

Açıklama: useState değer ve atayıcı döndürür.

3 useState parçalarını eşleştir

Kavram Anlamı
useState Hook
count Değer
setCount Atayıcı
0 Başlangıç değeri

Başlangıç bölümündeki tüm dersler