client swr dedup
本地来源:Knowledge/World/项目/Practice/Claude-Skills/vercel-react-best-practices/rules/client-swr-dedup.md
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):
function UserList() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('/api/users')
.then(r => r.json())
.then(setUsers)
}, [])
}
Correct (multiple instances share one request):
import useSWR from 'swr'
function UserList() {
const { data: users } = useSWR('/api/users', fetcher)
}
For immutable data:
import { useImmutableSWR } from '@/lib/swr'
function StaticContent() {
const { data } = useImmutableSWR('/api/config', fetcher)
}
For mutations:
import { useSWRMutation } from 'swr/mutation'
function UpdateButton() {
const { trigger } = useSWRMutation('/api/user', updateUser)
return <button onClick={() => trigger()}>Update</button>
}
Reference: https://swr.vercel.app
本文档为站内渲染。原始文件本地路径:saas/source/knowledge-world/Knowledge-World-项目-Practice-Claude-Skills-vercel-react-best--a860aa.md(仅本地保留,不入库不部署)