#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Custom React Hooks

Custom HTTP Hooks

A custom HTTP hook is a reusable function, named with a use prefix, that wraps the repetitive work of sending a request from a React component: tracking a loading flag, storing the response data, catching errors and cleaning up if the component disappears. Once written, any component can fetch data in one line instead of copying the same useState and useEffect code again and again.

The code every fetch repeats

Without a hook, each component that loads data needs three pieces of state, an effect, a try and catch block, a check of response.ok and a way to ignore results that arrive after the user has moved on. Multiply that by every list, profile and dashboard widget, and small inconsistencies creep in. One component forgets the error state, another never resets loading. A custom hook puts the logic in one tested place.

Writing a useFetch hook

import { useState, useEffect } from 'react';

export function useFetch(url) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (!url) return;
    const controller = new AbortController();

    async function load() {
      setIsLoading(true);
      setError(null);
      try {
        const res = await fetch(url, { signal: controller.signal });
        if (!res.ok) throw new Error(`Request failed: ${res.status}`);
        setData(await res.json());
      } catch (err) {
        if (err.name !== 'AbortError') setError(err.message);
      } finally {
        if (!controller.signal.aborted) setIsLoading(false);
      }
    }

    load();
    return () => controller.abort();
  }, [url]);

  return { data, error, isLoading };
}

// Using it
function UserList() {
  const { data: users, error, isLoading } = useFetch('/api/users');

  if (isLoading) return <p>Loading users...</p>;
  if (error) return <p role="alert">{error}</p>;
  return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}

What each part is doing

  • The dependency array [url] reruns the request whenever the URL changes, for example when a search term or page number is part of it.
  • AbortController cancels the old request in the cleanup function. If the URL changes quickly, a slow earlier response cannot overwrite newer data.
  • Ignoring AbortError stops a deliberate cancellation from showing up as an error message.
  • Returning an object lets callers rename fields, as data: users shows.

Each component that calls useFetch gets its own independent state. Hooks share logic, not data. Two components calling the same URL will make two requests unless you add caching.

Hooks for requests triggered by the user

Loading on mount is only half the story. Saving a form needs a request that runs when a button is clicked. A second style of hook returns a function instead of running in an effect: const { sendRequest, isLoading, error } = useHttp();, where sendRequest(url, options) sets the loading flag, calls fetch and returns the parsed body. Wrap sendRequest in useCallback so its identity stays stable if components list it as an effect dependency.

A trap with request options

A common bug is passing an options object straight into a hook that lists it as a dependency: useFetch(url, { headers: { ... } }). A new object is created on every render, the effect sees a "changed" dependency, fetches again, updates state, re-renders, and loops forever. Fix it by defining constant options outside the component, memoising them with useMemo, or depending only on primitive values such as the URL and method. Also make sure every hook call sits at the top level of the component, never inside an if or a loop, so React can match state to the right hook on every render.

What to take away

Move loading, error and data handling into a use-prefixed function, cancel stale requests with AbortController, keep dependencies to stable values, and offer a callable version for user-triggered requests. Components then focus on what to show instead of how to fetch. For heavier needs such as caching and background refresh, libraries built on this same idea exist, but writing your own first teaches how they work.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course