
SWR Has a Free API That Makes Data Fetching in React Effortless
SWR (stale-while-revalidate) is Vercel's data-fetching library for React. Its API is deceptively simple — but under the hood, it handles caching, revalidation, pagination, and optimistic updates. Basic Usage: One Hook, Full Cache import useSWR from " swr " ; const fetcher = ( url : string ) => fetch ( url ). then ( r => r . json ()); function Profile () { const { data , error , isLoading , isValidating , mutate } = useSWR ( " /api/user " , fetcher ); if ( isLoading ) return < Spinner /> ; if ( error ) return < Error message = { error . message } /> ; return < div > { data . name } { isValidating && < RefreshIcon /> } < /div> ; } SWR returns stale data instantly, then revalidates in the background. Conditional Fetching // Only fetch when userId exists const { data } = useSWR ( userId ? `/api/users/ ${ userId } ` : null , fetcher ); // Dependent fetching — wait for first request const { data : user } = useSWR ( " /api/user " , fetcher ); const { data : projects } = useSWR ( user ? `/api/
Continue reading on Dev.to React
Opens in a new tab



