mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-02-13 17:55:46 +01:00
- Fix syntax errors in skills markdown files (.github/skills, .opencode/skills) - Change typescript to tsx for code blocks with JSX - Replace ellipsis (...) in array examples with valid syntax - Separate CSS from TypeScript into distinct code blocks - Convert JavaScript object examples to valid JSON in docs - Fix enum definitions with proper comma separation
57 lines
1.1 KiB
Markdown
57 lines
1.1 KiB
Markdown
---
|
|
title: Use SWR for Automatic Deduplication
|
|
impact: MEDIUM-HIGH
|
|
impactDescription: automatic deduplication
|
|
tags: client, swr, deduplication, data-fetching
|
|
---
|
|
|
|
## Use SWR for Automatic Deduplication
|
|
|
|
SWR enables request deduplication, caching, and revalidation across component instances.
|
|
|
|
**Incorrect (no deduplication, each instance fetches):**
|
|
|
|
```tsx
|
|
function UserList() {
|
|
const [users, setUsers] = useState([]);
|
|
useEffect(() => {
|
|
fetch("/api/users")
|
|
.then((r) => r.json())
|
|
.then(setUsers);
|
|
}, []);
|
|
}
|
|
```
|
|
|
|
**Correct (multiple instances share one request):**
|
|
|
|
```tsx
|
|
import useSWR from "swr";
|
|
|
|
function UserList() {
|
|
const { data: users } = useSWR("/api/users", fetcher);
|
|
}
|
|
```
|
|
|
|
**For immutable data:**
|
|
|
|
```tsx
|
|
import { useImmutableSWR } from "@/lib/swr";
|
|
|
|
function StaticContent() {
|
|
const { data } = useImmutableSWR("/api/config", fetcher);
|
|
}
|
|
```
|
|
|
|
**For mutations:**
|
|
|
|
```tsx
|
|
import { useSWRMutation } from "swr/mutation";
|
|
|
|
function UpdateButton() {
|
|
const { trigger } = useSWRMutation("/api/user", updateUser);
|
|
return <button onClick={() => trigger()}>Update</button>;
|
|
}
|
|
```
|
|
|
|
Reference: [https://swr.vercel.app](https://swr.vercel.app)
|