File tree Expand file tree Collapse file tree 2 files changed +24
-3
lines changed
Expand file tree Collapse file tree 2 files changed +24
-3
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Example: WindowResizeListener
3+ *
4+ * Explanation:
5+ * - Demonstrates subscribing to global events (window resize) inside useEffect.
6+ * - Teaches why cleanup is required to prevent leaks.
7+ * - Common real-world pattern: resize listeners, keyboard shortcuts, scroll tracking.
8+ */
9+ import { useEffect , useState } from "react" ;
10+
11+ export default function WindowResizeListener ( ) {
12+ const [ size , setSize ] = useState ( { w : window . innerWidth , h : window . innerHeight } ) ;
13+
14+ useEffect ( ( ) => {
15+ const handler = ( ) => setSize ( { w : window . innerWidth , h : window . innerHeight } ) ;
16+ window . addEventListener ( "resize" , handler ) ;
17+ return ( ) => window . removeEventListener ( "resize" , handler ) ;
18+ } , [ ] ) ;
19+
20+ return < p > Window size: { size . w } × { size . h } </ p > ;
21+ }
Original file line number Diff line number Diff line change 99import BasicLog from "./examples/01_BasicLog" ;
1010import EffectCleanup from "./examples/02_EffectCleanup" ;
1111import DependencyArray from "./examples/03_DependencyArray" ;
12- // import WindowResizeListener from "./examples/WindowResizeListener ";
12+ import WindowResizeListener from "./examples/04_WindowResizeListner " ;
1313// import FetchData from "./examples/FetchData";
1414// import MultipleEffects from "./examples/MultipleEffects";
1515// import EffectVsLayoutEffect from "./examples/EffectVsLayoutEffect";
@@ -51,9 +51,9 @@ export default function UseEffectShowcase() {
5151 < DependencyArray />
5252 </ Demo >
5353
54- { /* <Demo title="4) WindowResizeListener — global event subscription">
54+ < Demo title = "4) WindowResizeListener — global event subscription" >
5555 < WindowResizeListener />
56- </Demo> */ }
56+ </ Demo >
5757
5858 { /* <Demo title="5) FetchData — async request with cleanup">
5959 <FetchData />
You can’t perform that action at this time.
0 commit comments