DEV Community

Aman Kureshi
Aman Kureshi

Posted on

๐Ÿงฉ React Custom Hooks โ€” Reuse Logic Like a Pro

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)