Skip to content

Commit ee0be1f

Browse files
committed
usestate hooks examples
1 parent a729670 commit ee0be1f

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Example: CounterBasic
3+
* What: Smallest possible useState example (number state).
4+
* Why: Shows initialization, reading state, and updating via setter.
5+
* Concepts: Primitive state, re-render on setState, direct vs functional form (intro).
6+
*/
7+
import { useState } from "react";
8+
9+
export default function CounterBasic() {
10+
// Initialize state with 0. useState returns [currentValue, setterFunction]
11+
const [count, setCount] = useState(0);
12+
13+
return (
14+
<div>
15+
{/* Display current count value */}
16+
<p>Count: {count}</p>
17+
18+
{/* Direct update: uses current count value directly */}
19+
<button onClick={() => setCount(count + 1)}>+1 (direct)</button>
20+
21+
{/* Functional update: safer, uses previous value from React */}
22+
<button onClick={() => setCount(c => c + 1)}>+1 (functional)</button>
23+
24+
{/* Reset counter to initial value */}
25+
<button onClick={() => setCount(0)}>Reset</button>
26+
</div>
27+
);
28+
}
29+
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Example: FunctionalUpdateVsStale
3+
* What: Demonstrates stale reads when batching multiple updates.
4+
* Why: Two direct updates can read the same old value; functional updates chain correctly.
5+
* Concepts: Batching, stale closure, functional updater pattern.
6+
*/
7+
import { useState } from "react";
8+
9+
export default function FunctionalUpdateVsStale() {
10+
const [n, setN] = useState(0);
11+
12+
// WRONG: Both setN calls read the same "n" value from render time
13+
// If n=5, both calls do setN(5+1), so final result is 6, not 7
14+
const wrong = () => {
15+
setN(n + 1); // reads current "n" (e.g., 5 -> 6)
16+
setN(n + 1); // reads the SAME "n" (5 -> 6 again!)
17+
};
18+
19+
// RIGHT: Each setN gets the latest value from React's state
20+
// First call: v=5 -> returns 6, Second call: v=6 -> returns 7
21+
const right = () => {
22+
setN(v => v + 1); // v is the most current value
23+
setN(v => v + 1); // v is updated from previous call
24+
};
25+
26+
return (
27+
<div>
28+
<p>n = {n}</p>
29+
{/* This will only add 1 instead of 2 due to stale closure */}
30+
<button onClick={wrong}>+2 (wrong)</button>
31+
{/* This correctly adds 2 by chaining updates */}
32+
<button onClick={right}>+2 (right)</button>
33+
</div>
34+
);
35+
}
36+

0 commit comments

Comments
 (0)