۱۴۰۴/۰۸/۰۴ Nebular

reduxt toolkit

Redux یک state manager هست که بهت اجازه میده state کل برنامه رو مرکزیت داده و به راحتی بین کامپوننت‌ها به اشتراک بذاری.

  • Store → جایی که کل state نگهداری میشه
  • Slice → یک بخش از state و actions مربوطه
  • Action → چیزی که میگه state باید تغییر کنه
  • Reducer → فانکشنی که state و action می‌گیره و state جدید رو برمی‌گردونه

Redux Toolkit (RTK) نسخه مدرن Redux هست که boilerplate خیلی کمتره و راحت‌تر میشه استفاده کرد.

مثال ساده با Redux Toolkit

Step 1: ایجاد Slice

// store/counterSlice.ts
import { createSlice } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
  name: "counter",
  initialState: { value: 0 },
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    reset: (state) => {
      state.value = 0;
    },
  },
});

export const { increment, decrement, reset } = counterSlice.actions;
export default counterSlice.reducer;

Step 2: ایجاد Store

// store/index.ts
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

// Types
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

Step 3: اتصال به React

// main.tsx یا index.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import { store } from "./store";
import App from "./App";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <Provider store={store}>
    <App />
  </Provider>
);

Step 4: استفاده در کامپوننت

import { useSelector, useDispatch } from "react-redux";
import { RootState, AppDispatch } from "./store";
import { increment, decrement, reset } from "./store/counterSlice";

export default function Counter() {
  const count = useSelector((state: RootState) => state.counter.value);
  const dispatch = useDispatch<AppDispatch>();

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
      <button onClick={() => dispatch(reset())}>Reset</button>
    </div>
  );
}

🔹 نکات کلیدی

  1. Redux Toolkit بهت اجازه میده state رو mutable بنویسی ولی در واقع immutable مدیریت میشه.
  2. createSlice هم state و هم actions رو با هم میسازه، دیگه نیازی به نوشتن action type دستی نیست.
  3. useSelector برای گرفتن state، useDispatch برای ارسال action.
  4. کل state برنامه در store ذخیره میشه، بنابراین تمام کامپوننت‌ها می‌تونن ازش استفاده کنند.
Accept Cookies
Accept Cookies
[your-shortcode]