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)