Özet - Zustand
- React Native kursu
- İleri seviye
- Ders 60/83
- 5 dk
create, action ve persist'i birleştirerek bir kalıcı sayaç yazarsın.
Özet - Zustand
Bu grupta Zustand, create, state okuma, action ve persist öğrendik. create store oluşturur; dönen hook'u bileşende çağırırsın. Seçici ile yalnızca ilgili alan değişince render tetiklenir. Action, set ile state günceller. persist ise state'i kalıcı yapar.
Şimdi bunları birleştirip kalıcı bir sayaç yazacağız. Store tanımı, okuma, artırma ve persist sarması birlikte gelir. Bu kalıp, Zustand ile tüm kalıcı uygulamaların iskeletidir.
Uygulama Özet - Kalıcı sayaç store'u
useCounter store'unu tanımla. persist ile sar. State: count: 0. Action: increment: () => set((s) => ({ count: s.count + 1 })). Persist name: 'counter-storage'. export const ile dışa aktar.
Başlangıç kodu
import { create } from 'zustand';
// useCounter'ı persist ile tanımlaÖrnek çözüm
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export const useCounter = create(persist((set) => ({
count: 0,
increment: () => set((s) => ({ count: s.count + 1 })),
}), { name: 'counter-storage' }));Uygulama Özet - Sayaç bileşeni
Counter bileşenini tamamla. const count = useCounter((s) => s.count) ile değeri oku. const increment = useCounter((s) => s.increment) ile action'ı al. <Text>{count}</Text> ve artırma butonu döndür.
Başlangıç kodu
import React from 'react';
import { Button, Text, View } from 'react-native';
export function Counter() {
// count ve increment'i seçici ile al; Text ve Button döndür
return null;
}Örnek çözüm
import React from 'react';
import { Button, Text, View } from 'react-native';
import { useCounter } from './useCounter';
export function Counter() {
const count = useCounter((s) => s.count);
const increment = useCounter((s) => s.increment);
return (
<View>
<Text>{count}</Text>
<Button title="Artir" onPress={() => increment()} />
</View>
);
}Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 Akış parçalarını eşle
| Kavram | Anlamı |
|---|---|
create |
Store oluşturur |
set |
State günceller |
(s) => s.count |
Seçici |
persist |
Kalıcı yapar |
2 Persist name değerini yaz
persist((set) => ({ count: 0 }), { name: '____' })
persist((set) => ({ count: 0 }), { name: 'counter-storage' })
Açıklama: counter-storage anahtar adıdır.