Custom hooks let you extract and reuse stateful logic across multiple components in React. They start with the word use
and follow the same rules as built-in hooks.
π Why use custom hooks?
β’ DRY (Don't Repeat Yourself) β avoid repeating the same logic
β’ Clean and readable code
β’ Easy testing and maintenance
π¨βπ§ Example: Create a custom hook to track window width
import { useState, useEffect } from "react";
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}
π§ Usage in a component:
function App() {
const width = useWindowWidth();
return <p>Current width: {width}px</p>;
}
π Key points:
β’ Custom hooks must start with use
β’ You can use other hooks inside them (useState, useEffect, etc.)
β’ Great for abstracting logic like timers, form validation, fetching, etc.
Custom hooks make your React apps more modular and maintainable. A power move for every React developer!
Top comments (0)