ما وراء useState: أنماط متقدمة لإدارة الحالة في React
مقدمة
بينما useState مثالي لحالة المكونات البسيطة، تتطلب التطبيقات المعقدة غالبًا حلولًا أكثر قوة. تستكشف هذه المقالة أنماط إدارة الحالة المتقدمة في React التي توفر تنظيمًا وأداءً وقابلية تطوير أفضل.
Context API
تسمح لك Context API بمشاركة الحالة عبر تطبيقك دون الحاجة إلى تمرير الخصائص بشكل متكرر (prop drilling).
import React, { createContext, useContext, useState } from 'react';
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
export const useTheme = () => useContext(ThemeContext);
الاستخدام:
import { useTheme } from './ThemeContext';
const MyComponent = () => {
const { theme, toggleTheme } = useTheme();
return (
<div style={{ backgroundColor: theme === 'light' ? 'white' : 'black', color: theme === 'light' ? 'black' : 'white' }}>
<p>الوضع الحالي: {theme}</p>
<button onClick={toggleTheme}>تبديل الوضع</button>
</div>
);
};
useReducer
useReducer مثالي لإدارة منطق الحالة المعقد، على غرار Redux ولكن داخل المكون.
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
العدد: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>زيادة</button>
<button onClick={() => dispatch({ type: 'decrement' })}>إنقاص</button>
</>
);
}
Zustand
Zustand هو حل صغير وسريع وقابل للتطوير لإدارة الحالة. يستخدم مبادئ Flux مبسطة.
npm install zustand
import { create } from 'zustand'
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}))
function Counter() {
const { count, increment, decrement } = useStore()
return (
<>
العدد: {count}
<button onClick={increment}>زيادة</button>
<button onClick={decrement}>إنقاص</button>
</>
)
}
خاتمة
useState هي نقطة بداية جيدة، لكن Context API و useReducer و Zustand توفر حلولًا أكثر قوة وقابلية للصيانة لإدارة الحالة المعقدة في تطبيقات React الخاصة بك. اختر النمط الذي يناسب متطلبات مشروعك على أفضل وجه.