Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
import { useState, useEffect } from 'react'; function WindowSize() { const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight, }); useEffect(() => { function handleResize() { setSize({ width: window.innerWidth, height: window.innerHeight, }); } window.addEventListener('resize', handleResize); // Cleanup removes the listener on unmount / before re-run return () => { window.removeEventListener('resize', handleResize); }; }, []); // only runs once – no dependencies return ( <p> Window: {size.width} × {size.height} </p> ); } function TimerDemo() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(id); // clear on unmount }, []); return <p>Seconds elapsed: {count}</p>; }
Result
Open