ReactIntermediate
Custom Hooks
পুনরাবৃত্ত logic-কে reusable hook-এ ভাগ করা — naming convention, rules ও ব্যবহার — বাংলায়।
7টি অংশবাংলা ভাষায়
কেন custom hook
যখন একই logic (fetch, window resize, toggle, local storage) অনেক component-এ দরকার — তখন সেটাকে custom hook-এ রাখুন। যেকোনো function যার নাম use দিয়ে শুরু এবং ভেতরে থাকা hook functions-কে call করে — সেটিই custom hook।
useFetchjsx
jsx
import { useEffect, useState } from "react";
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let cancelled = false;
setLoading(true);
fetch(url)
.then((r) => {
if (!r.ok) throw new Error("Bad response");
return r.json();
})
.then((json) => {
if (!cancelled) setData(json);
})
.catch((e) => {
if (!cancelled) setError(e);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [url]);
return { data, loading, error };
}
// ব্যবহার
function Profile() {
const { data: user, loading } = useFetch("/api/users/1");
if (loading) return <p>Loading…</p>;
return <h1>{user.name}</h1>;
}useLocalStorage
Persist datajsx
jsx
import { useEffect, useState } from "react";
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
const [theme, setTheme] = useLocalStorage("theme", "light");Rules of Hooks
- শুধু top-level — loops/conditions/নেস্টেড function-এ hook লেখা যাবে না
- শুধু function component বা custom hook-এ call করুন
- নাম অবশ্যই
useদিয়ে শুরু — lint তখন নিয়ম verify করতে পারে - Hook return — array বা object, যেটা ব্যবহারে সুবিধা
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।