Skip to content

Commit 9d2a6e3

Browse files
committed
blog: hook comp
1 parent 8d5299d commit 9d2a6e3

File tree

3 files changed

+88
-4
lines changed

3 files changed

+88
-4
lines changed

public/posts/posts.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,16 @@
11
[
2+
{
3+
"slug": "react-hooks-comparison",
4+
"title": "React Hooks Showdown: useMemo vs useCallback vs useState vs useEffect",
5+
"date": "2025-12-15",
6+
"updated": "2025-12-15",
7+
"description": "A comprehensive comparison of React's most commonly used hooks, explaining when and why to use each.",
8+
"tags": ["react", "hooks", "frontend", "javascript", "webdev"],
9+
"category": "gist",
10+
"filename": "react-hooks-comparison.txt",
11+
"authors": ["fezcode"],
12+
"image": "/images/defaults/sina-salehian-HqmTUJD73mM-unsplash.jpg"
13+
},
214
{
315
"slug": "react-magic-markdown-components",
416
"title": "React Magic: Rendering Components from Markdown Links",
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
## 1. useState: The Memory
2+
3+
**What it does:** Allows a functional component to "remember" information between renders.
4+
5+
**When to use:** Whenever you have data that changes over time and needs to trigger a re-render to update the UI (e.g., form inputs, toggle states, counters).
6+
7+
```javascript
8+
const [count, setCount] = useState(0);
9+
10+
// Update state
11+
setCount(count + 1);
12+
```
13+
14+
## 2. useEffect: The Side Effect
15+
16+
**What it does:** Performs side effects in functional components. "Side effects" are things like data fetching, subscriptions, or manually changing the DOM.
17+
18+
**When to use:** When you need to do something *after* the component renders or when a specific value changes.
19+
20+
```javascript
21+
useEffect(() => {
22+
// This runs after every render
23+
document.title = `You clicked ${count} times`;
24+
25+
// Optional cleanup mechanism
26+
return () => {
27+
// Clean up code here
28+
};
29+
}, [count]); // Only re-run if 'count' changes
30+
```
31+
32+
## 3. useMemo: The Calculator
33+
34+
**What it does:** Memoizes (caches) the *result* of a calculation. It only re-calculates the value when one of its dependencies changes.
35+
36+
**When to use:** Optimization. Use it to avoid expensive calculations on every render.
37+
38+
```javascript
39+
const expensiveValue = useMemo(() => {
40+
return computeExpensiveValue(a, b);
41+
}, [a, b]); // Only re-compute if 'a' or 'b' changes
42+
```
43+
44+
*Note: Don't overuse this. Memoization has its own cost.*
45+
46+
## 4. useCallback: The Function Saver
47+
48+
**What it does:** Memoizes a *function definition*. It returns the same function instance between renders unless its dependencies change.
49+
50+
**When to use:** Optimization. Primarily useful when passing callbacks to optimized child components (like those wrapped in `React.memo`) to prevent unnecessary re-renders of the child.
51+
52+
```javascript
53+
const handleClick = useCallback(() => {
54+
doSomething(a, b);
55+
}, [a, b]); // Function identity remains stable unless 'a' or 'b' changes
56+
```
57+
58+
## Summary Table
59+
60+
| Hook | Returns | Purpose | Re-runs when... |
61+
| :--- | :--- | :--- | :--- |
62+
| **useState** | `[state, setter]` | Manage state | Setter is called |
63+
| **useEffect** | `undefined` | Side effects | Dependencies change |
64+
| **useMemo** | Calculated Value | Cache expensive calculation | Dependencies change |
65+
| **useCallback** | Memoized Function | Stable function identity | Dependencies change |
66+
67+
## Key Difference: useMemo vs useCallback
68+
69+
* `useMemo` caches the **result** of a function call.
70+
* `useCallback` caches the **function itself**.
71+
72+
> `useCallback(fn, deps)` is equivalent to `useMemo(() => fn, deps)`.

src/pages/apps/SpriteEditorPage.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useState, useEffect } from 'react';
1+
import React, {useState, useEffect, useCallback} from 'react';
22
import {
33
PencilSimple,
44
Eraser,
@@ -80,7 +80,7 @@ const SpriteEditorPage = () => {
8080
}, [gridSize]);
8181

8282
const saveToHistory = () => {
83-
if (history.length > 20) {
83+
if (history.length > 150) {
8484
setHistory([...history.slice(1), [...pixels]]);
8585
} else {
8686
setHistory([...history, [...pixels]]);
@@ -127,12 +127,12 @@ const SpriteEditorPage = () => {
127127
}
128128
};
129129

130-
const undo = () => {
130+
const undo = useCallback(() => {
131131
if (history.length === 0) return;
132132
const previousState = history[history.length - 1];
133133
setPixels(previousState);
134134
setHistory(history.slice(0, -1));
135-
};
135+
}, [history]);
136136

137137
const clearCanvas = () => {
138138
saveToHistory();

0 commit comments

Comments
 (0)