الدرس الخامس عشر: استخدام الـ Hooks في React
في هذا الدرس، سنتعرف على مفهوم React Hooks وكيفية استخدامها في تطبيقات React. سنشرح أهم الـ Hooks المستخدمة في React مثل useState، useEffect، useContext، و useReducer. بالإضافة إلى ذلك، سنتناول الفرق بين class components و function components باستخدام الـ hooks.
1. ما هي React Hooks؟
React Hooks هي دوال تسمح لك باستخدام ميزات React مثل الحالة (state) و التأثيرات الجانبية (side effects) داخل function components. قبل تقديم الـ Hooks، كان يمكن استخدام هذه الميزات فقط داخل class components. لكن مع React 16.8، أصبح من الممكن استخدام هذه الميزات في function components أيضًا، مما يجعل كتابة الكود أبسط وأوضح.
2. أهم الـ Hooks في React
1. useState
useState هو أول وأبسط Hook في React. يتيح لك إدارة الحالة (state) في function components.
كيفية استخدام useState:
import React, { useState } from 'react';
function Counter() {
// إنشاء state لتخزين قيمة العداد
const [count, setCount] = useState(0);
// دالة لزيادة القيمة
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
الشرح:
useState(0)يقوم بإنشاء state باسمcountويعطيه قيمة مبدئية وهي 0.setCountهي دالة مخصصة لتحديث state.- عند الضغط على الزر، يتم تحديث state وبالتالي إعادة render المكون.
2. useEffect
useEffect هو Hook يستخدم لإجراء التأثيرات الجانبية (side effects) مثل جلب البيانات أو التفاعل مع DOM بعد أن يتم تحديث state أو props.
كيفية استخدام useEffect:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setData(data));
}, []); // التفاعل يحدث مرة واحدة عند تحميل المكون فقط (حيث [] هي الـ dependency)
if (!data) {
return <div>Loading...</div>;
}
return (
<div>
<h1>Fetched Data</h1>
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
export default DataFetcher;
الشرح:
useEffectيتم استدعاؤه بعد كل عملية render.- نستخدمه لجلب البيانات من API في هذا المثال، وذلك باستخدام fetch.
[]في الـ dependency array يعني أن التأثير سيحدث مرة واحدة فقط عند تحميل المكون.
3. useContext
useContext هو Hook يستخدم للوصول إلى القيم المخزنة في Context بدون الحاجة لاستخدام props.
كيفية استخدام useContext:
import React, { useContext } from 'react';
const MyContext = React.createContext('default value');
function Display() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
function App() {
return (
<MyContext.Provider value="Hello from Context!">
<Display />
</MyContext.Provider>
);
}
export default App;
الشرح:
useContext(MyContext)يمكنه الوصول إلى القيمة التي تم تعيينها في Context Provider.- في المثال، قمنا بتمرير قيمة داخل
MyContext.Providerفي المكون App، ثم استخدمناuseContextداخلDisplayللحصول على هذه القيمة.
4. useReducer
useReducer هو Hook مشابه لـ useState، لكنه يتيح لك إدارة state بشكل أكثر تعقيدًا عندما يكون لديك منطق متعدد أو يحتاج إلى التفاعل مع أنواع متعددة من الأحداث.
كيفية استخدام useReducer:
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:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
export default Counter;
الشرح:
- في هذا المثال،
useReducerيتم استخدامه لإدارة state للعداد. dispatchيستخدم لإرسال action إلى reducer، الذي يحدد كيفية تحديث الـ state.
3. الفرق بين الـ Class Components و Function Components مع الـ Hooks
1. Class Components
في class components، نستخدم this.state و this.setState() لإدارة state، و lifecycle methods (مثل componentDidMount() و componentDidUpdate()) لإدارة التأثيرات الجانبية.
مثال على class component:
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
2. Function Components مع Hooks
في function components، لا نحتاج إلى constructor أو lifecycle methods. بدلاً من ذلك، نستخدم useState و useEffect وغيرهما من hooks لإدارة state والتأثيرات الجانبية.
مثال على function component مع useState:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
4. الختام
في هذا الدرس، تعلمنا عن React Hooks وأهم الـ Hooks المستخدمة في React مثل useState، useEffect، useContext، و useReducer. كما استعرضنا الفرق بين class components و function components في استخدام الـ Hooks.
الـ Hooks توفر طريقة أكثر مرونة وبساطة لكتابة المكونات في React، وتساعد على تقليل الكود المعقد وتحسين أداء التطبيقات.
اكتشاف المزيد من كود التطور
اشترك للحصول على أحدث التدوينات المرسلة إلى بريدك الإلكتروني.


