Custom Hooks allow you to extract and reuse stateful logic across multiple components. They are JavaScript functions whose names start with use
and can call other hooks internally.
import { useState, useEffect } 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; } export default useWindowWidth;
import React from 'react'; import useWindowWidth from './useWindowWidth'; function ShowWidth() { const width = useWindowWidth(); return ( <div style={{ textAlign: 'center', marginTop: '30px', fontSize: '18px' }}> <p>Current window width: <strong>{width}px</strong></p> </div> ); }
Here, useWindowWidth
listens to window resize events and provides the current window width. This logic is cleanly separated and can be reused anywhere by just calling the hook.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!