0Pricing
React Native Academy · Ders

Zustand Store Oluşturma

Zustand'ı yükleyin, create ile bir store tanımlayın, durum özellikleri ve eylem işlevleri ekleyin ve store'un Redux mimarisinden farkını anlayın.

Zustand Store Oluşturma, CoddyKit'te ücretsiz bir React Native Academy dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, React Native Academy öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. React Native Academy kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

What Is Zustand?

Zustand (German for 'state') is a minimal, fast state management library for React. Unlike Redux, it requires no boilerplate like action creators, reducers, or a Provider wrapper. You define a store as a single function, and any component can subscribe to it with a simple hook. It is ideal for apps that need global state without the complexity of Redux Toolkit.

Installing Zustand

Install Zustand from npm with a single command. It has zero dependencies and is compatible with React Native out of the box. The package is lightweight — under 1 kB gzipped — which keeps your app's bundle size small.

npm install zustand

Creating Your First Store

Call create from Zustand and pass it a function that receives set and returns an object containing your state properties and actions. The returned value is a custom hook — conventionally named useXxxStore — that components call to access the store.

import { create } from 'zustand';

interface CounterStore {
  count: number;
  increment: () => void;
  decrement: () => void;
  reset: () => void;
}

export const useCounterStore = create<CounterStore>((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
  reset: () => set({ count: 0 }),
}));

The set Function

The set function is how Zustand updates state. You can pass it either a partial state object (Zustand merges it with existing state) or a callback that receives the current state and returns the updated portion. Zustand automatically notifies all subscribers when state changes.

// Partial object — Zustand merges it
set({ count: 0 });

// Callback — use when new value depends on previous value
set((state) => ({ count: state.count + 1 }));

// Replace entire state (pass true as second arg)
set(() => ({ count: 0, name: 'reset' }), true);

No Provider Needed

One of Zustand's biggest advantages over Redux is that you do not need to wrap your component tree in a Provider. The store lives outside React and components subscribe to it directly via the returned hook. This means you can use the store anywhere — in components, in callbacks, or even outside React components.

// No Provider needed — just use the hook anywhere
function CounterDisplay() {
  const count = useCounterStore((state) => state.count);
  return <Text>Count: {count}</Text>;
}

function CounterButtons() {
  const increment = useCounterStore((state) => state.increment);
  const decrement = useCounterStore((state) => state.decrement);
  return (
    <View>
      <Button title='+' onPress={increment} />
      <Button title='-' onPress={decrement} />
    </View>
  );
}

Subscribing to Specific State

Pass a selector function to the store hook to subscribe to only part of the state. The component re-renders only when the selected value changes. Without a selector, the component re-renders whenever any part of the store updates, which can hurt performance in large stores.

// Only re-renders when count changes
const count = useCounterStore((state) => state.count);

// Only re-renders when user.name changes
const username = useUserStore((state) => state.user.name);

// Without selector — re-renders on ANY store change (avoid this)
const everything = useCounterStore();

Accessing the Store Outside React

Zustand stores expose a getState() method that reads the current state synchronously without hooks. There is also a subscribe() method for non-React subscriptions and a setState() method for imperative updates. This is useful in utility functions, API interceptors, or navigation helpers that run outside React component lifecycle.

// Access store state anywhere — no hooks required
import { useCounterStore } from './counterStore';

// Read state outside React
const currentCount = useCounterStore.getState().count;

// Update state outside React
useCounterStore.getState().increment();

// Subscribe outside React
const unsub = useCounterStore.subscribe((state) => {
  console.log('Count changed to:', state.count);
});

Async Actions in Zustand

Zustand actions can be async — just mark the function async and call set after the await. You do not need special async utilities like Redux's createAsyncThunk. You can add loading and error state directly to the store and update them inside the async action.

export const usePostsStore = create<PostsStore>((set) => ({
  posts: [],
  loading: false,
  error: null,
  fetchPosts: async () => {
    set({ loading: true, error: null });
    try {
      const res = await fetch('https://api.example.com/posts');
      const data = await res.json();
      set({ posts: data, loading: false });
    } catch (e) {
      set({ error: 'Failed to load', loading: false });
    }
  },
}));

Comparing Zustand and Redux

Redux Toolkit is more structured and provides stronger conventions for large teams, time-travel debugging, and complex state. Zustand excels when you need global state with minimal ceremony — a single file, no action types, no Provider. Both are valid choices; pick Zustand for small-to-medium apps or when you want to move fast without Redux boilerplate.

Organizing Multiple Stores

In larger apps, split your state into multiple focused stores rather than one massive store. For example, create useAuthStore, useCartStore, and useSettingsStore separately. Each store file is small, independently testable, and imported only by the components that need it. This prevents unrelated state changes from triggering unnecessary re-renders.

// stores/authStore.ts
export const useAuthStore = create<AuthStore>((set) => ({ /* ... */ }));

// stores/cartStore.ts
export const useCartStore = create<CartStore>((set) => ({ /* ... */ }));

// Component imports only what it needs
import { useAuthStore } from '../stores/authStore';
import { useCartStore } from '../stores/cartStore';

Immer Middleware for Complex Updates

If your state is deeply nested and you want mutating-style updates (like Redux Toolkit's Immer integration), wrap the store creator with Zustand's immer middleware. With Immer, you can write state.user.preferences.theme = 'dark' instead of spreading every level of the object manually.

import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';

export const useSettingsStore = create(immer<SettingsStore>((set) => ({
  user: { name: '', preferences: { theme: 'light', notifications: true } },
  setTheme: (theme) => set((state) => {
    state.user.preferences.theme = theme; // Immer makes this safe
  }),
})));

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: Zustand creates global stores with minimal boilerplate using a single create call, no Provider is required because the store lives outside the React tree, and async actions work natively by marking store functions as async. Next up we explore reading and updating Zustand store state in components.

Sıkça Sorulan Sorular

“Zustand Store Oluşturma” dersi ücretsiz mi?

Evet — “Zustand Store Oluşturma” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve React Native Academy kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. React Native Academy kursu toplamda 4 dersten oluşur.

“Zustand Store Oluşturma” dersinde ne öğreneceğim?

Zustand'ı yükleyin, create ile bir store tanımlayın, durum özellikleri ve eylem işlevleri ekleyin ve store'un Redux mimarisinden farkını anlayın. React Native Academy ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

React Native Academy öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te React Native Academy, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.

“Zustand Store Oluşturma” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu React Native Academy dersinde kod yazıp çalıştırabilir miyim?

Evet. Her React Native Academy dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Zustand Store Oluşturma
  2. Bileşenlerde Store Durumunu Okuma ve Güncelleme
  3. AsyncStorage ile Zustand Durumunu Kalıcılaştırma
  4. Dilimler Kalıbı ve DevTools Entegrasyonu
← React Native Academy Sayfasına Dön