Custom Hook React JS 2025
✅ Create Custom Hook in React JS 2025
Custom hooks are a powerful feature in React that allow you to extract component logic into reusable functions. These are just normal JavaScript functions whose names start with use
, and they can call other hooks like useState
, useEffect
, etc.
🎯 Why Use Custom Hooks?
- Reusability of logic
- Cleaner and more maintainable components
- Better separation of concerns
📦 Example: useFetch Custom Hook
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url);
const json = await res.json();
setData(json);
setLoading(false);
} catch (err) {
setError(err);
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
export default useFetch;
📄 How to Use It in a Component
import React from 'react';
import useFetch from './useFetch';
const PokemonList = () => {
const { data, loading, error } = useFetch('https://pokeapi.co/api/v2/pokemon');
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
return (
{data.results.map((pokemon) => (
- {pokemon.name}
))}
);
};
export default PokemonList;