React — Custom Hooks
Custom Hooks are JavaScript functions that start with use
and let you reuse logic across components. They follow the same rules as built-in hooks.
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;
}
function App() {
const width = useWindowWidth();
return <h1>Window width: {width}px</h1>;
}