File tree Expand file tree Collapse file tree 2 files changed +37
-3
lines changed Expand file tree Collapse file tree 2 files changed +37
-3
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Example: EffectCleanup
3+ *
4+ * Explanation:
5+ * - Shows how to return a cleanup function from useEffect.
6+ * - Common for unsubscribing from events, canceling timers, or cleaning resources.
7+ * - Demonstrates mount → effect → cleanup → unmount lifecycle.
8+ */
9+ import { useEffect , useState } from "react" ;
10+
11+ export default function EffectCleanup ( ) {
12+ const [ visible , setVisible ] = useState ( true ) ;
13+
14+ return (
15+ < div >
16+ < button onClick = { ( ) => setVisible ( v => ! v ) } >
17+ { visible ? "Hide" : "Show" } Timer
18+ </ button >
19+ { visible && < Timer /> }
20+ </ div >
21+ ) ;
22+ }
23+
24+ function Timer ( ) {
25+ useEffect ( ( ) => {
26+ const id = setInterval ( ( ) => console . log ( "tick" ) , 1000 ) ;
27+ return ( ) => {
28+ console . log ( "cleanup: clearing interval" ) ;
29+ clearInterval ( id ) ;
30+ } ;
31+ } , [ ] ) ;
32+
33+ return < p > Timer running (check console)…</ p > ;
34+ }
Original file line number Diff line number Diff line change 77 */
88
99import BasicLog from "./examples/01_BasicLog" ;
10- // import EffectCleanup from "./examples/EffectCleanup ";
10+ import EffectCleanup from "./examples/02_EffectCleanup " ;
1111// import DependencyArray from "./examples/DependencyArray";
1212// import WindowResizeListener from "./examples/WindowResizeListener";
1313// import FetchData from "./examples/FetchData";
@@ -43,9 +43,9 @@ export default function UseEffectShowcase() {
4343 < BasicLog />
4444 </ Demo >
4545
46- { /* <Demo title="2) EffectCleanup — cleanup on unmount">
46+ < Demo title = "2) EffectCleanup — cleanup on unmount" >
4747 < EffectCleanup />
48- </Demo> */ }
48+ </ Demo >
4949
5050 { /* <Demo title="3) DependencyArray — [] vs deps vs no deps">
5151 <DependencyArray />
You can’t perform that action at this time.
0 commit comments