React custom hooks allow you to extract component logic into reusable functions, keeping your components clean and focused. By abstracting stateful behavior into hooks, you can share logic across multiple components without duplicating code.
1. Creating a Custom Hook
Custom hooks are JavaScript functions whose names start with use. They can call other React hooks internally:
// useWindowSize Custom Hook
import { useState, useEffect } from 'react';
export function useWindowSize() {
const [size, setSize] = useState({ width: 0, height: 0 });
useEffect(() => {
const handleResize = () => setSize({ width: window.innerWidth, height: window.innerHeight });
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
2. Hooks Rules & Custom State Management
All custom React hooks must conform to standard React lifecycle execution limits:
- Top-Level Execution: Hooks must be called at the very top of React functional components. Never call hooks inside conditional statements (
if), loops, or nested structures. - Hook Naming: Ensure custom hooks begin with the prefix
use(e.g.useFetch,useAuth) so that compiler linters can enforce React rules accurately.
Extracting code loops into custom state managers improves component separation of concerns and facilitates testing.React custom hooks allow you to extract component logic into reusable functions, keeping your components clean and focused. By abstracting stateful behavior into hooks, you can share logic across multiple components without duplicating code.
1. Creating a Custom Hook
Custom hooks are JavaScript functions whose names start with use. They can call other React hooks internally:
// useWindowSize Custom Hook
import { useState, useEffect } from 'react';
export function useWindowSize() {
const [size, setSize] = useState({ width: 0, height: 0 });
useEffect(() => {
const handleResize = () => setSize({ width: window.innerWidth, height: window.innerHeight });
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
2. Hooks Rules & Custom State Management
All custom React hooks must conform to standard React lifecycle execution limits:
- Top-Level Execution: Hooks must be called at the very top of React functional components. Never call hooks inside conditional statements (
if), loops, or nested structures. - Hook Naming: Ensure custom hooks begin with the prefix
use(e.g.useFetch,useAuth) so that compiler linters can enforce React rules accurately.
Extracting code loops into custom state managers improves component separation of concerns and facilitates testing.