Custom Hooks তৈরি করা

Custom Hooks in React.js – বিস্তারিত গাইড

React-এর সবচেয়ে শক্তিশালী ফিচারের মধ্যে একটি হলো Hooks। এর ভিতরে আপনি useState, useEffect, useRef, useMemo ইত্যাদি ব্যবহার করেন।

কিন্তু কখনো কখনো একই লজিক আপনাকে বিভিন্ন কম্পোনেন্টে বারবার ব্যবহার করতে হয়। এই পুনরাবৃত্ত কোড কমানোর জন্য React দিয়েছে –

✨ Custom Hooks

Custom Hooks হলো আপনার নিজের তৈরি JavaScript function, যার ভিতরে আপনি React Hooks ব্যবহার করতে পারেন এবং যেকোনো কম্পোনেন্টে পুনরায় ব্যবহার করতে পারেন।


📌 Custom Hook কী?

Custom Hook হলো একটি function যা React-এর বিল্ট-ইন Hook ব্যবহার করে তৈরি হয় এবং কোনো কমন লজিককে পুনরায় ব্যবহারযোগ্য (Reusable) করে তোলে।

Custom Hook-এর নাম অবশ্যই use দিয়ে শুরু হতে হবে। যেমন: useFetch, useAuth, useLocalStorage


🎯 কেন Custom Hook ব্যবহার করা হয়?

  • একই লজিক বারবার লিখতে না হয়
  • কোড ক্লিন ও রিইউজেবল হয়
  • কম্পোনেন্টকে হালকা করা যায়
  • লজিককে UI থেকে আলাদা করা যায়
  • ডাটা ফেচিং, ফর্ম হ্যান্ডলিং, authentication ইত্যাদি সহজ হয়

🧩 Custom Hook-এর Basic Structure

function useCustomHook() {
    // Hook logic here
    return someValue;
}

এটি একটি সাধারণ JavaScript function এর মতোই, কিন্তু এর ভিতরে React Hooks ব্যবহার করা যায়।


📘 Example 1: Custom Hook for Window Width (Responsive Design)

Step 1: Custom Hook তৈরি

// useWindowWidth.js
import { useState, useEffect } from "react";

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return width;
}

export default useWindowWidth;

Step 2: Component-এ ব্যবহার

import useWindowWidth from "./useWindowWidth";

function App() {
  const width = useWindowWidth();

  return (
     <div>
<h1>Window Width: {width}px</h1>
</div> ); } export default App;

👉 এখন যেকোনো কম্পোনেন্টে এই হুক ব্যবহার করলে window width পাবেন।


📘 Example 2: Custom Hook for Fetching Data (useFetch)

Step 1: Hook তৈরি

// useFetch.js
import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await fetch(url);
        const json = await res.json();
        setData(json);
      } catch (err) {
        setError(err);
      }
      setLoading(false);
    }

    fetchData();
  }, [url]);

  return { data, loading, error };
}

export default useFetch;

Step 2: Component-এ ব্যবহার

import useFetch from "./useFetch";

function UserList() {
  const { data, loading, error } = useFetch("https://jsonplaceholder.typicode.com/users");

  if (loading) return <h2>Loading...</h2>;
  if (error) return <h2>Error Occurred</h2>

  return (
    <div>
<h1>User List</h1>
{data.map(user => (
<p key={user.id}>{user.name}</p>
))}
</div> ); } export default UserList;

👉 এখন পুরো ডাটা ফেচিং লজিক মাত্র এক লাইনে ব্যবহার করতে পারছেন।
const { data, loading, error } = useFetch(url);


📘 Example 3: Local Storage Custom Hook

// useLocalStorage.js
import { useState } from "react";

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : initialValue;
  });

  const setStoredValue = newValue => {
    setValue(newValue);
    localStorage.setItem(key, JSON.stringify(newValue));
  };

  return [value, setStoredValue];
}

export default useLocalStorage;

এই Hook ব্যবহার করে সহজেই Local Storage হ্যান্ডেল করা যায়।


🧠 Custom Hook লেখার নিয়ম (Best Practices)

  • নাম অবশ্যই use দিয়ে শুরু করতে হবে
  • হুকের ভিতরে React Hooks ব্যবহার করা যাবে
  • লজিককে UI থেকে আলাদা রাখা
  • Reusable হওয়া উচিত
  • Side effect থাকলে useEffect ব্যবহার করুন

✔️ সারসংক্ষেপ

Custom Hooks React-এর একটি অসাধারণ ফিচার যা আপনার কোডকে করে:

  • Re-usable
  • Readable
  • Organized
  • Clean

ওয়েব অ্যাপ্লিকেশনে ডাটা ফেচিং, authentication, input handling, debouncing, throttling—সব ক্ষেত্রেই Custom Hooks অত্যন্ত শক্তিশালী টুল।

👼 Quiz
/

লোড হচ্ছে...

Interview Questions:

1. Custom Hook কী এবং এর সুবিধা কী?

Custom Hook হলো নিজের তৈরি Hook যা একাধিক component এ একই logic reuse করতে সাহায্য করে। এটি কোড duplication কমায়, maintainability বাড়ায় এবং পরিষ্কার architecture তৈরি করে।

2. Custom Hook এর নাম use দিয়ে শুরু করা কেন বাধ্যতামূলক?

React Hooks এর rule অনুযায়ী Hook এর নাম অবশ্যই use দিয়ে শুরু হতে হবে। এতে React বুঝতে পারে এটি Hook এবং linting tool গুলো ভুল ব্যবহার ধরতে পারে।