Custom hooks are your own functions that use built-in React hooks and allow reusing logic between components.
Simple analogy: Imagine you are a chef and often make béchamel sauce. Instead of doing it from scratch every time: melt butter, add flour, pour milk, stir — you just say: "Make béchamel sauce!" (calling a custom hook).
Example 1: useAuth (authorization check)
1import { useState, useEffect } from 'react';23function useAuth() {4 const [user, setUser] = useState(null);5 const [loading, setLoading] = useState(true);67 useEffect(() => {8 fetch('/api/me')9 .then(res => res.json())10 .then(setUser)11 .finally(() => setLoading(false));12 }, []);1314 return { user, loading, isAuth: !!user };15}16};1718// Usage in any component19function Profile() {20 const { user, loading } = useAuth();21 if (loading) return <Spinner />;22 return <h1>Hello, {user.name}!</h1>;23}
Example 2: useWindowSize (window size)
1function useWindowSize() {2 const [size, setSize] = useState({3 width: window.innerWidth,4 height: window.innerHeight5 });67 useEffect(() => {8 const handler = () => setSize({9 width: window.innerWidth,10 height: window.innerHeight11 });12 window.addEventListener('resize', handler);13 return () => window.removeEventListener('resize', handler);14 }, []);1516 return size;17}
Custom hook rules: