Clean • Professional
In React, Hooks allow you to use state and lifecycle features in functional components. Sometimes, multiple components need the same logic, such as fetching data, managing forms, or handling animations.
Instead of repeating code, Custom Hooks allow you to extract reusable logic into a separate function.
A Custom Hook is a JavaScript function whose name starts with use and can call other hooks inside it.
Syntax:
function useCustomHook() {
// Use other hooks like useState, useEffect
const [state, setState] = useState(initialValue);
// Return values/functions
return { state, setState };
}
Example – Custom Hook for Fetching Data
Suppose multiple components need to fetch data from an API. Instead of repeating useState and useEffect, we can create a useFetch 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;
import React from "react";
import useFetch from "./useFetch";
function Users() {
const { data, loading, error } = useFetch("<https://jsonplaceholder.typicode.com/users>");
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default Users;
useFetch handles all fetching logic.Users component only consumes the returned values.useLocalStorage → Sync state with localStorageuseForm → Handle form state and validationuseWindowSize → Track window dimensionsusePrevious → Store previous state or props