Careeroza
Real World Example
Real World: Notification bell (LinkedIn, Facebook)
One small feature usually uses several hooks together: state for open/closed, an effect to load new notifications, and a ref to close the dropdown when you click outside.
function NotificationBell() {
const [open, setOpen] = useState(false); // useState: open / closed
const [items, setItems] = useState([]);
const boxRef = useRef(null); // useRef: the dropdown element
useEffect(() => { // useEffect: load data
fetch('/api/notifications').then((r) => r.json()).then(setItems);
}, []);
useEffect(() => { // useEffect: click outside closes it
const close = (e) => !boxRef.current?.contains(e.target) && setOpen(false);
document.addEventListener('click', close);
return () => document.removeEventListener('click', close);
}, []);
return <div ref={boxRef}><button onClick={() => setOpen(!open)}>🔔 {items.length}</button></div>;
}