xonecas.io
556
Bn

bees-nest / files

bees-nest / .opencode / skills / vercel-react-best-practices / rules / client-swr-dedup.md

1.1 KB
1---
2title: Use SWR for Automatic Deduplication
3impact: MEDIUM-HIGH
4impactDescription: automatic deduplication
5tags: client, swr, deduplication, data-fetching
6---
7
8## Use SWR for Automatic Deduplication
9
10SWR enables request deduplication, caching, and revalidation across component instances.
11
12**Incorrect (no deduplication, each instance fetches):**
13
14```tsx
15function UserList() {
16  const [users, setUsers] = useState([])
17  useEffect(() => {
18    fetch('/api/users')
19      .then(r => r.json())
20      .then(setUsers)
21  }, [])
22}
23```
24
25**Correct (multiple instances share one request):**
26
27```tsx
28import useSWR from 'swr'
29
30function UserList() {
31  const { data: users } = useSWR('/api/users', fetcher)
32}
33```
34
35**For immutable data:**
36
37```tsx
38import { useImmutableSWR } from '@/lib/swr'
39
40function StaticContent() {
41  const { data } = useImmutableSWR('/api/config', fetcher)
42}
43```
44
45**For mutations:**
46
47```tsx
48import { useSWRMutation } from 'swr/mutation'
49
50function UpdateButton() {
51  const { trigger } = useSWRMutation('/api/user', updateUser)
52  return <button onClick={() => trigger()}>Update</button>
53}
54```
55
56Reference: [https://swr.vercel.app](https://swr.vercel.app)