Redux Toolkit, Redux’un karmaşık görünen yapılarını daha basit ve anlaşılır hale getiren bir kütüphane.


Store Yapısı

configureStore kullanıyoruz. Bu, createStore + combineReducers işini tek başına hallediyor.

import { configureStore } from "@reduxjs/toolkit";
import customerReducer from "./features/customerSlice";
import accountReducer from "./features/accountSlice";

const store = configureStore({
  reducer: {
    customer: customerReducer,
    account: accountReducer,
  },
});

export default store;

Slice Yapısı

createSlice reducer + action creator’ı birlikte tanımlar.

import { createSlice } from "@reduxjs/toolkit";

const customerSlice = createSlice({
  name: "customer",
  initialState: {
    fullName: "",
    nationalID: "",
    createdAt: "",
  },
  reducers: {
    createCustomer: {
      reducer(state, action) {
        state.fullName = action.payload.fullName;
        state.nationalID = action.payload.nationalID;
        state.createdAt = action.payload.createdAt;
      },
      prepare(fullName, nationalID) {
        return {
          payload: {
            fullName,
            nationalID,
            createdAt: new Date().toISOString(),
          },
        };
      },
    },
    updateName(state, action) {
      state.fullName = action.payload;
    },
  },
});

export const { createCustomer, updateName } = customerSlice.actions;
export default customerSlice.reducer;

Burada dikkat:


Asenkron İşlemler (createAsyncThunk)

API çağrıları gibi durumlar için createAsyncThunk kullanıyoruz.

import { createAsyncThunk } from "@reduxjs/toolkit";

export const fetchAddress = createAsyncThunk(
  "customer/fetchAddress",
  async (nationalID) => {
    const res = await fetch(`https://api.example.com/address/${nationalID}`);
    const data = await res.json();
    return { address: data.address };
  }
);

Reducer tarafında otomatik pending, fulfilled, rejected action’ları oluşuyor: