Tool for HR, Hiring Managers, and the Leadership Team

Custom Hooks in React

Custom Hooks in React

Custom Hooks in React are reusable JavaScript functions that start with the prefix use and allow you to extract and reuse stateful logic across multiple components.

They are built using React’s built-in hooks like useState, useEffect, useRef, etc.

Definition (Simple Interview Answer)

A custom hook is a function that:

  • Starts with use (important convention)

  • Uses one or more React hooks internally

  • Encapsulates reusable logic

  • Can be shared across components

Why do we need Custom Hooks?

In real applications, multiple components often reuse the same logic, such as:

  • API calls

  • Form handling

  • Authentication checks

  • Local storage management

  • Debouncing input

Instead of duplicating code, we extract it into a custom hook.

Example

Example: useFetch custom hook

import { useState, useEffect } from "react";

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

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(url);
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
}

export default useFetch;

Usage in Component:

function Users() {
  const { data, loading, error } = useFetch("https://api.example.com/users");

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error occurred</p>;

  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

Key Rules of Custom Hooks

  1. Must start with use

  2. Can call other hooks inside

  3. Should not be called conditionally

  4. Must follow Rules of Hooks (same as built-in hooks)

  5. Returns reusable logic/data, not JSX

Benefits

  • Code reusability

  • Cleaner components (separation of logic)

  • Better maintainability

  • Easier testing of logic

  • Avoids duplication

Common Interview Follow-up Questions

1. How is a custom hook different from a normal function?

  • Custom hook uses React hooks internally

  • It maintains React state lifecycle

  • Normal function does not track React lifecycle/state

2. Can custom hooks return JSX?

No. Custom hooks should return data or functions, not UI.

3. Can we use multiple custom hooks in one component?

Yes, absolutely. That’s a common pattern.

One-Line Summary

A custom hook is a reusable function in React that encapsulates stateful logic using built-in hooks, allowing clean and modular code across components.