Skip to content

Commit 0c30347

Browse files
committed
usestate hooks examples
1 parent ee0be1f commit 0c30347

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Example: LazyInit
3+
* What: Run an expensive init only once using a lazy initializer.
4+
* Why: Avoids recomputing heavy initial value on every render.
5+
* Concepts: Lazy initialization, avoiding unnecessary work, first-render semantics.
6+
*/
7+
import { useState } from "react";
8+
9+
// Simulate an expensive calculation (like reading from localStorage, complex math, etc.)
10+
function expensiveInit() {
11+
console.log("expensive init (runs once)"); // This should only log once!
12+
return 42;
13+
}
14+
15+
export default function LazyInit() {
16+
// Pass a FUNCTION to useState instead of calling expensiveInit() directly
17+
// This ensures expensiveInit only runs on the first render, not every render
18+
const [value, setValue] = useState(() => expensiveInit());
19+
20+
return (
21+
<div>
22+
<p>value = {value}</p>
23+
{/* Each click re-renders the component, but expensiveInit won't run again */}
24+
<button onClick={() => setValue(v => v + 1)}>inc</button>
25+
</div>
26+
);
27+
}
28+
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* Example: ObjectAndArrayUpdates
3+
* What: Update nested structures immutably (object + array).
4+
* Why: React state must be treated as immutable to trigger correct re-renders.
5+
* Concepts: Spread syntax, map/filter, structural sharing.
6+
*/
7+
import { useState } from "react";
8+
9+
type Todo = { id: string; text: string; done: boolean };
10+
type User = { name: string; city: string };
11+
12+
export default function ObjectAndArrayUpdates() {
13+
// Object state: must create new object when updating
14+
const [user, setUser] = useState<User>({ name: "Ava", city: "Pune" });
15+
16+
// Array state: must create new array when updating
17+
const [todos, setTodos] = useState<Todo[]>([
18+
{ id: "1", text: "Learn useState", done: true },
19+
{ id: "2", text: "Practice examples", done: false },
20+
]);
21+
22+
// Update object immutably: spread existing user, override city
23+
const moveCity = () => setUser(u => ({ ...u, city: "Bangalore" }));
24+
25+
// Update array immutably: spread existing todos, add new item at end
26+
const addTodo = () => setTodos(ts => [...ts, {
27+
id: crypto.randomUUID(),
28+
text: "New item",
29+
done: false
30+
}]);
31+
32+
// Update specific array item: map through, update matching id, keep others same
33+
const toggle = (id: string) => setTodos(ts =>
34+
ts.map(t => (t.id === id ? { ...t, done: !t.done } : t))
35+
);
36+
37+
// Remove array item: filter out the item with matching id
38+
const remove = (id: string) => setTodos(ts => ts.filter(t => t.id !== id));
39+
40+
return (
41+
<div>
42+
{/* Display current user info */}
43+
<p>User: {user.name}{user.city}</p>
44+
<button onClick={moveCity}>Move city</button>
45+
<hr />
46+
<button onClick={addTodo}>Add todo</button>
47+
48+
{/* Render each todo with toggle and remove functionality */}
49+
<ul>
50+
{todos.map(t => (
51+
<li key={t.id}>
52+
<label>
53+
<input
54+
type="checkbox"
55+
checked={t.done}
56+
onChange={() => toggle(t.id)}
57+
/>
58+
{t.text}
59+
</label>
60+
<button onClick={() => remove(t.id)}>x</button>
61+
</li>
62+
))}
63+
</ul>
64+
</div>
65+
);
66+
}
67+

0 commit comments

Comments
 (0)