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