Inspired by Vercel/swr, but no API needed, as it revalidates data through static pages.
Only one api call per session is needed to synchronize local and remote clocks. We recommend using the middleware.
npm install next-swr
// _app file
import { useRevalidate } from 'next-swr'
function App({ Component, pageProps }) {
useRevalidate(pageProps) // Optional
return <Component {...pageProps} />
}
// middleware
import { middlewareClock } from 'next-swr'
export const config = { matcher: ['/swr'] }
export const middleware = middlewareClock(async () = > { ... });
// page files
import { getStaticPropsRevalidate, useRevalidate } from 'next-swr'
function Page({ swr, ...props }) {
useRevalidate({ swr }) // Only if not in _app file
return <Component {...props} />
}
export const getStaticProps = getStaticPropsRevalidate(async (ctx) => {
// get data...
return {
props: { data },
revalidate: 10
}
)
It is better to put useRevalidate
only in the _app file as it reduces the number of renders and calls to the backend.
In this case, custom settings for each page can be returned via the swr object in getStaticProps.
swr
: an object of options for this hook
function Page({ swr, ...props }) {
useRevalidate({ swr: {...swr, revalidateOnFocus: false } })
or
export const getStaticProps = getStaticPropsRevalidate(async () => {
// get data...
return {
props: { data },
swr: {
revalidate_f: 1,
refreshInterval: 30_000
}
}
})
revalidateIfStale = true
: automatically revalidate even if there is stale datarevalidateOnMount = true
: enable or disable first automatic revalidation when component is mountedrevalidateOnFocus = true
: automatically revalidate when window gets focusedrefreshInterval
:- Disabled by default:
refreshInterval = 0
- If set to a number, polling interval in milliseconds (min 50 ms)
- If set to a function, the function will receive the latest data and should return the interval in milliseconds
- Disabled by default:
dedupingInterval
: dedupe revalidate at least this time interval in milliseconds. Default is the elapsed time in the previous revalidationrevalidate_f
: sets a fixed revalidate ongetStaticProps
. The default is automatic, beingrevalidate
plus the elapsed time in the previous revalidationswrPath
: sets the endpoint to return the server time to synchronize expiration. Default is/swr
which can be provided bymiddlewareClock
Not compatible with Next.js v13.3.0 due to a bug.
The MIT License.