React Hooks সম্পূর্ণ গাইড — useState থেকে Custom Hooks পর্যন্ত
React Hooks ব্যবহার করে functional component-এ state ও lifecycle manage করুন। সব built-in hooks এবং custom hooks তৈরির পদ্ধতি শিখুন।
React Hooks ২০১৯ সালে React 16.8-এ introduce হয়েছিল এবং এটি React দুনিয়াকে বদলে দিয়েছে। Class component-এর যুগ প্রায় শেষ — এখন সব কিছু functional component ও hooks দিয়েই হয়।
useState — State Management
useState হলো সবচেয়ে বেশি ব্যবহৃত hook। এটি component-এর state manage করে।
Basic usage: const [count, setCount] = useState(0);
State update করতে: setCount(prev => prev + 1);
মনে রাখুন — state update asynchronous। তাই previous state-এর উপর ভিত্তি করে update করলে সবসময় function form ব্যবহার করুন।
useEffect — Side Effects
useEffect দিয়ে component mount, update, unmount-এ side effects handle করা যায়। API call, subscription, timer — সব এখানে যায়।
Dependency array গুরুত্বপূর্ণ: useEffect(fn, []) মানে শুধু mount-এ, useEffect(fn, [count]) মানে count পরিবর্তনে। Cleanup function return করুন — এটি unmount-এ চলে।
useContext — Global State
Prop drilling সমস্যা সমাধান করে। Context create করুন, Provider দিয়ে wrap করুন, যেকোনো child component-এ useContext দিয়ে access করুন।
useMemo ও useCallback — Performance
useMemo expensive calculation memoize করে — শুধু dependency পরিবর্তন হলে recalculate করে। useCallback function memoize করে — child component-এ pass করার সময় unnecessary re-render আটকায়।
useRef — DOM Reference
DOM element-এ direct access দরকার হলে useRef ব্যবহার করুন। Input focus, video play/pause, scroll position — এই কাজগুলোতে useRef দরকার হয়।
Custom Hooks তৈরি
Reusable logic custom hook-এ বের করুন। যেমন API fetch করার logic — useFetch নামে একটি custom hook বানান এবং যেকোনো component থেকে ব্যবহার করুন। Custom hook-এর নাম সবসময় "use" দিয়ে শুরু করতে হয়।