Skip to main content

Custom Hooks

Custom Hooks allow you to extract complex state logic and side effects out of large components into dedicated, reusable functions.

If two functions share similar logic, you extract the shared logic to a third function. Custom Hooks follow the exact same principle, but they allow you to utilize React's built-in hooks natively.

Rules of Custom Hooks

  1. They must be standard JavaScript functions.
  2. Their names must start with the word use (e.g., useFetch, useAuth). This naming convention tells React that the function may call other Hooks and should be subject to standard Hook linting rules.
  3. They can return whatever data types you prefer (Arrays, Objects, or primitives).

Creating a useFetch Hook

A standard pattern in React is fetching data from an API and handling the loading state. Doing this manually in every component causes massive duplication.

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

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

useEffect(() => {
setIsLoading(true);
fetch(url)
.then((res) => res.json())
.then((json) => {
setData(json);
setIsLoading(false);
});
}, [url]);

return { data, isLoading };
}

Now, any component in your application can easily fetch data with a single line of code.

// App.jsx
import { useFetch } from './useFetch';

export default function App() {
const { data, isLoading } = useFetch("https://api.example.com/users");

if (isLoading) return <div>Loading users...</div>;

return <div>{JSON.stringify(data)}</div>;
}