A custom hook is reusable logic pulled out into its own function, named starting with `use...`. When multiple components need the same state/effect logic, you can write it once as a hook instead of copy-pasting it everywhere.
jsx
import { useEffect, useState } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
function App() {
const width = useWindowWidth();
return <p>Window width is {width}px</p>;
}The `useWindowWidth` hook keeps the browser width in state and updates it every time the window is resized. The component just calls the hook and displays the width in the UI.
You should see
The browser window's width is shown in pixels and updates every time you resize the window.Info
Since we set up an event listener, we remove it again with a cleanup function. Skip that and you risk memory leaks or duplicated listeners.