1import { useState, useEffect } from 'react';
2
3const WindowResizeTracker = () => {
4 const [windowSize, setWindowSize] = useState({
5 width: window.innerWidth,
6 height: window.innerHeight,
7 });
8
9 useEffect(() => {
10 // Event handler to update dimensions
11 const handleResize = () => {
12 setWindowSize({
13 width: window.innerWidth,
14 height: window.innerHeight,
15 });
16 };
17
18 // Add event listener
19 window.addEventListener('resize', handleResize);
20
21 // Cleanup function: VERY IMPORTANT
22 // Remove event listener when component unmounts
23 return () => {
24 window.removeEventListener('resize', handleResize);
25 };
26 }, []); // Empty dependency array because we want the effect only on mount
27
28 return (
29 <div className="window-size">
30 <h2>Window Dimensions:</h2>
31 <p>Width: {windowSize.width}px</p>
32 <p>Height: {windowSize.height}px</p>
33 </div>
34 );
35};
36
37// Another example: Timer with cleanup
38const Timer = () => {
39 const [seconds, setSeconds] = useState(0);
40 const [isRunning, setIsRunning] = useState(false);
41
42 useEffect(() => {
43 let intervalId;
44
45 if (isRunning) {
46 // Start timer
47 intervalId = setInterval(() => {
48 setSeconds((prevSeconds) => prevSeconds + 1);
49 }, 1000);
50 }
51
52 // Cleanup function
53 return () => {
54 if (intervalId) {
55 clearInterval(intervalId);
56 }
57 };
58 }, [isRunning]); // Triggers only when isRunning changes
59
60 const handleToggle = () => {
61 setIsRunning((prev) => !prev);
62 };
63
64 const handleReset = () => {
65 setIsRunning(false);
66 setSeconds(0);
67 };
68
69 return (
70 <div className="timer">
71 <h2>Timer</h2>
72 <p>Time elapsed: {seconds} seconds</p>
73 <button onClick={handleToggle}>{isRunning ? 'Pause' : 'Start'}</button>
74 <button onClick={handleReset}>Reset</button>
75 </div>
76 );
77};