React Native'de Yeni Context API ile Global State Yönetimi
React Native'de Yeni Context API ile Global State Yönetimi React Native uygulamalarında state yönetimi, özellikle büyük ölçekli projelerde kritik bir konudur. Redux gibi kütüphaneler popüler olsa da, React'in sunduğu Context API ile daha hafif ve...
Published by Adem Hatay on
📝 Bu blog yazısı yapay zeka tarafından oluşturulmuş, güncel teknoloji bilgileri ve best practices içerir.
React Native’de Yeni Context API ile Global State Yönetimi
React Native uygulamalarında state yönetimi, özellikle büyük ölçekli projelerde kritik bir konudur. Redux gibi kütüphaneler popüler olsa da, React’in sunduğu Context API ile daha hafif ve basit çözümler üretmek mümkün. Bu yazıda, React Native’de Context API kullanarak nasıl etkili bir global state yönetimi yapabileceğimizi adım adım inceleyeceğiz.
Context API Nedir?
Context API, React’in bileşenler arasında veri paylaşımını kolaylaştıran bir özelliğidir. Props drilling (veriyi birçok bileşen katmanından geçirme) sorununu çözmek için tasarlanmıştır.
import React, { createContext, useContext, useState } from 'react';
const AppContext = createContext();
export const AppProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [theme, setTheme] = useState('light');
return (
<AppContext.Provider value={{ user, setUser, theme, setTheme }}>
{children}
</AppContext.Provider>
);
};
export const useAppContext = () => useContext(AppContext);
Adım Adım Context API Kurulumu
1. Context Dosyası Oluşturma
Öncelikle bir context dosyası oluşturalım. context/AppContext.js
:
import React, { createContext, useContext, useReducer } from 'react';
const initialState = {
user: null,
theme: 'light',
notifications: [],
};
const reducer = (state, action) => {
switch (action.type) {
case 'SET_USER':
return { ...state, user: action.payload };
case 'TOGGLE_THEME':
return { ...state, theme: state.theme === 'light' ? 'dark' : 'light' };
case 'ADD_NOTIFICATION':
return { ...state, notifications: [...state.notifications, action.payload] };
default:
return state;
}
};
const AppContext = createContext();
export const AppProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
};
export const useAppContext = () => useContext(AppContext);
2. Uygulamayı Provider ile Sarma
App.js
dosyasında uygulamamızı oluşturduğumuz provider ile sarmalayalım:
import React from 'react';
import { AppProvider } from './context/AppContext';
import MainScreen from './screens/MainScreen';
const App = () => {
return (
<AppProvider>
<MainScreen />
</AppProvider>
);
};
export default App;
3. Context Kullanımı
Artık herhangi bir bileşende context’i kullanabiliriz:
import React from 'react';
import { View, Text, Button } from 'react-native';
import { useAppContext } from '../context/AppContext';
const ProfileScreen = () => {
const { state, dispatch } = useAppContext();
const toggleTheme = () => {
dispatch({ type: 'TOGGLE_THEME' });
};
return (
<View style={{ backgroundColor: state.theme === 'light' ? '#fff' : '#333' }}>
<Text>Kullanıcı: {state.user?.name || 'Misafir'}</Text>
<Button title="Tema Değiştir" onPress={toggleTheme} />
</View>
);
};
export default ProfileScreen;
Performans Optimizasyonları
Context API kullanırken performans sorunları yaşamamak için dikkat edilmesi gerekenler:
- Bölünmüş Contextler: Tüm state’i tek bir context’te tutmak yerine, mantıksal olarak ayırabilirsiniz (AuthContext, ThemeContext gibi).
// AuthContext.js
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
return (
<AuthContext.Provider value={{ user, setUser }}>
{children}
</AuthContext.Provider>
);
};
- Memoization: Sık değişen değerler için
useMemo
kullanın:
const AppProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const contextValue = useMemo(() => ({ state, dispatch }), [state]);
return (
<AppContext.Provider value={contextValue}>
{children}
</AppContext.Provider>
);
};
- Selectors: Büyük state objelerinde sadece ihtiyaç duyulan parçayı seçmek için özel hook’lar yazın:
export const useUser = () => {
const { state } = useAppContext();
return state.user;
};
Best Practices
- Context’i Abartmayın: Yerel state için useState, bileşenler arası paylaşılan state için Context kullanın.
- Type Safety: TypeScript ile çalışıyorsanız, context için tipler tanımlayın.
- Test Edilebilirlik: Context’leri kolayca mock’layabilecek şekilde tasarlayın.
- Documentation: Özellikle takım projelerinde context’lerin nasıl kullanılacağını belgeleyin.
Redux vs Context API
Özellik | Context API | Redux |
---|---|---|
Kurulum Kolaylığı | ✔️ | ❌ |
Öğrenme Eğrisi | ✔️ | ❌ |
DevTools | ❌ | ✔️ |
Middleware | ❌ | ✔️ |
Performans | Orta | İyi |
Kullanım Senaryosu | Küçük/Orta uygulamalar | Büyük uygulamalar |
Sonuç ve Tavsiyeler
React Native’de global state yönetimi için Context API, özellikle küçük ve orta ölçekli uygulamalar için
💡 Hızlı Özet
Bu yazıda React Native’de Yeni Context API ile Global State Yönetimi konusunu detaylı olarak ele aldık. Öğrendiklerinizi projelerinizde uygulayarak deneyim kazanmayı unutmayın!
🔗 Faydalı Kaynaklar:
📱 Beni Takip Edin:
- GitHub: @ademhatay
- Blog: ademhatay.dev
⭐ Bu yazı faydalı olduysa, projenizde kullanmaya başladığınızda deneyimlerinizi benimle paylaşmayı unutmayın!