React & Redux
Herkese merhabalar,
Yazılım dünyasının yeni ve popüler teknolojilerinden React programlama dili ile veri yönetiminde kullanılan Redux’ı anlatmaya çalışacağım.
React’ta component’ler arası veri paylaşımında, state management büyük rol oynamaktadır. Sayfa sayısının ve state’lerin az olduğu projelerde, localStorage veya sessionStorage gibi yapılarla state yönetimini sürdürebiliriz. Fakat state sayısı arttıkça bu yapılar ihtiyacımızı karşılamak için yetersiz kalmaktadır. Bu noktada Redux kütüphanesi, merkezi, esnek ve dayanıklı bir state yönetim mekanizması sunmaktadır.
Redux kütüphanesi, yukarıda da bahsettiğimiz gibi veriyi merkezi bir depoda tutarak component’ler arasındaki veri paylaşımını daha düzenli ve kolay hale getirir. Burada redux’ın store, actions ve reducers temel kavramlarından kısaca bahsedecek olursam;
- Store: Uygulamanın global durumunu tutar.
- Actions: Store’a veri gönderme işlemini tanımlar. Genelde bir olay sonucu tetiklenen bir işlem olarak düşünülür.
- Reducers: Store’daki durumu değiştiren fonksiyonlardır.
Örnek bir uygulama ile react’ta redux kullanımını netleştirelim.
React ve Redux ile Basit Bir Sepet Uygulaması Yazımı
Basit bir sepet uygulaması yani sepete ekleme, sepetten kaldırma ve sepeti temizleme işlemleri ile react’ta redux kullanımını ele alalım. Örneğimizde 3 tane default verilmiş bir ürün listesi tanımlayıp, sonrasında bu ürünleri Sepete ekleyip, sepetten silip ve sepetten kaldırma işlemlerini yapabiliyor olacağız. Uygulamamızın son durumdaki ekran görüntüsü şöyle olacak diyebiliriz:
-Sepete ekle butonuna tıkladıkça, ürünler aşağıdaki gibi olacak:
Görüldüğü üzere, sepetteki ürün bilgileri adet bilgisi vs redux tarafında tutuluyor ve bu sepetteki bilgiler değişiklik gösterdikçe componentlerimiz de tekrar render ediliyor olacak.
Proje Yapısı:
Uygulamamızın mimarisi ve ekran yapısı aşağıdaki gibi basit şekilde gösterecek olursak:
Burada kodlamaya başlamadan önce, redux kütüphanesini eklemek için aşağıdaki komutu terminal ekranında çalıştırmamız gerekiyor.
npm install redux react-reduxYukarıdaki örnek projenin kod bilgilerini de sizlerle aşağıdaki gibi paylaşabilirim.
Get Talha Erdogan’s stories in your inbox
Join Medium for free to get updates from this writer.
Redux/Actions.js
export const addCart = (cart) => ({
type: 'ADD_TO_CART',
payload: cart,
});
export const removeCart = (id) => ({
type: 'REMOVE_FROM_CART',
payload: id,
});
export const clearCart = () => ({
type: 'CLEAR_CART'
});— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Redux/Reducer.js
// Başlangıç durumu: Sepetteki ürünler
const initialState = {
cart: [],
};
// Reducer (durum değişikliklerini yöneten fonksiyon)
function cartReducer(state = initialState, action) {
switch (action.type) {
case 'ADD_TO_CART':
// Ürün sepete ekleniyor
const existingProduct = state.cart.find(
(product) => product.id === action.payload.id
);
if (existingProduct) {
// Ürün zaten sepette var, miktarını artır
return {
...state,
cart: state.cart.map((product) =>
product.id === action.payload.id
? { ...product, quantity: product.quantity + 1 }
: product
),
};
} else {
// Ürün sepette yoksa, yeni ürün ekle
return { ...state, cart: [...state.cart, { ...action.payload, quantity: 1 }] };
}
case 'REMOVE_FROM_CART':
// Ürün sepetteki listeden çıkarılıyor
return {
...state,
cart: state.cart.filter((product) => product.id !== action.payload),
};
case 'CLEAR_CART':
// Sepeti temizle
return { ...state, cart: [] };
default:
return state;
}
}
export default cartReducer;— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Redux/Store.js
import { createStore } from 'redux';
import cartReducer from './reducer';
const store = createStore(cartReducer);
export default store;— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Components/Cart.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { removeCart,clearCart } from '../redux/actions';
const Cart = () => {
const cart = useSelector((state) => state.cart); // Redux store'undaki sepet
const dispatch = useDispatch(); // Redux dispatch fonksiyonu
const removeFromCart = (productId) => {
dispatch(removeCart(productId));
};
const clearCartFull = () => {
dispatch(clearCart());
};
const calculateTotal = () => {
return cart.reduce((total, product) => total + product.price * product.quantity, 0);
};
return (
<div>
<div className="cart">
<h3>Sepetiniz</h3>
{cart.length === 0 ? (
<p>Sepetiniz boş.</p>
) : (
<div>
<ul>
{cart.map((product) => (
<li key={product.id}>
{product.name} - {product.quantity} adet - {product.price * product.quantity}₺
<button onClick={() => removeFromCart(product.id)}>Kaldır</button>
</li>
))}
</ul>
<div className="total">Toplam: {calculateTotal()}₺</div>
<button className="clear-cart-button" onClick={clearCartFull}>
Sepeti Temizlee!
</button>
</div>
)}
</div>
</div>
);
};
export default Cart;— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Components/ProductList.js
import React from 'react';
import { useDispatch } from 'react-redux';
import { addCart } from '../redux/actions';
const products = [
{ id: 1, name: 'Laptop', price: 5000 },
{ id: 2, name: 'Telefon', price: 2000 },
{ id: 3, name: 'Tablet', price: 1500 },
];
const ProductList = () => {
// Redux dispatch fonksiyonu
const dispatch = useDispatch();
const addToCart = (product) => {
dispatch(addCart(product));
};
return (
<div>
<h2>Ürünler</h2>
<div className="product-list">
{products.map((product) => (
<div key={product.id} className="product-item">
<h3>{product.name}</h3>
<p>Fiyat: {product.price}₺</p>
<button onClick={() => addToCart(product)}>Sepete Ekle</button>
</div>
))}
</div>
</div>
);
};
export default ProductList;— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
App.js
import './App.css';
import ProductList from './components/ProductList';
import Cart from './components/Cart';
function App() {
return (
<div className="app">
<h1>Alışveriş Sepeti</h1>
<ProductList />
<Cart />
</div>
);
}
export default App;— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
İndex.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/store'; // store'u import ediyoruz
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);Böylelikle, yazılım dünyasının popüler teknolojilerinden olan React programlama dili ile veri yönetiminde kullanılan Redux’ı anlatmaya çalıştım. Umarım faydalı olmuştur.
Bir başka yazıda görüşmek dileğiyle…
Hoşçakalın.








