Skip to content

Commit b83404a

Browse files
committed
Useeffect hook example 2
1 parent 5e75a2e commit b83404a

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

src/hooks/useEffect/useEffect.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88

99
import 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 />

0 commit comments

Comments
 (0)