examples/swr-site/content/en/index.mdx
import { Features } from '@app/_components/features' import { Callout, Tabs } from 'nextra/components'
<Tabs items={['JavaScript', 'C++', {label:'C', disabled: true}, 'Python', 'TypeScript', 'GraphQL', 'Rust', 'C#', 'Go', 'HTML', 'CSS', 'plaintext', 'bash']} defaultIndex={1}>
<Tabs.Tab>
js filename="hi.js" import { useState, useEffect } from 'react';
</Tabs.Tab>
<Tabs.Tab>
cpp filename="hi.cpp" #include <iostream>
</Tabs.Tab>
<Tabs.Tab>
c filename="hi.c" #include <stdio.h>
</Tabs.Tab>
<Tabs.Tab>
c filename="hi.c" #include <stdio.h>
</Tabs.Tab>
</Tabs>
The name "SWR" is derived from stale-while-revalidate, a HTTP cache
invalidation strategy popularized by
HTTP RFC 5861. SWR is a strategy to first
return the data from cache (stale), then send the fetch request (revalidate),
and finally come with the up-to-date data.
And the UI will be always fast and reactive.
</Callout> <div className="mt-16 mb-20 text-center"> [Get Started](/docs/getting-started) · [Examples](/examples/basic) · [Blog](/blog) · [GitHub Repository](https://github.com/vercel/swr) </div>import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
- if (error) return <div>failed to load</div>
+ if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
In this example, the useSWR hook accepts a key string and a fetcher
function. key is a unique identifier of the data (normally the API URL) and
will be passed to fetcher. fetcher can be any asynchronous function which
returns the data, you can use the native fetch or tools like Axios.
The hook returns 2 values: data and error, based on the status of the
request.
With just one single line of code, you can simplify the logic of data fetching in your project, and also have all these amazing features out-of-the-box:
SWR has you covered in all aspects of speed, correctness, and stability to help you build better experiences:
And a lot more.
SWR is created by the same team behind Next.js, the React framework. Follow @vercel on Twitter for future project updates.
Feel free to join the discussions on GitHub!