github vercel/swr 2.0.0-beta.4

latest releases: v2.2.6-beta.2, v2.2.6-beta.1, v2.2.6-beta.0...
pre-release23 months ago

Highlights

Preload API (#2026)

SWR now has a preload API that you can call programmatically to kick off the request early. For example, you can do preload('/api/user', fetcher) even outside of React:

import { useState } from 'react'
import useSWR, { preload } from 'swr'

const fetcher = (url) => fetch(url).then((res) => res.json())

// Preload the resource before rendering the User component below,
// this prevents potential waterfalls in your application.
// You can also start preloading when hovering the button or link, too.
preload('/api/user', fetcher)

function User() {
  const { data } = useSWR('/api/user', fetcher)
  ...
}

export default function App() {
  const [show, setShow] = useState(false)
  return (
    <div>
      <button onClick={() => setShow(true)}>Show User</button>
      {show ? <User /> : null}
    </div>
  )
}

So at the moment of clicking the button and actually rendering the User component, the resource is likely loaded already. If the request depends on some props or states, you can also preload it when hovering the button:

function App({ userId }) {
  const [show, setShow] = useState(false)
  return (
    <div>
      <button
        onClick={() => setShow(true)}
        onHover={() => preload('/api/user?id=' + userId, fetcher)}
      >
        Show User
      </button>
      {show ? <User /> : null}
    </div>
  )
}

Demo: https://codesandbox.io/s/swr-preloading-14bikv?file=/src/App.js

Function as SWRConfig value (#2024)

A new way to extend the SWR global configuration:

<SWRConfig value={{ revalidateOnFocus: false, dedupingInterval: 5000 }}>
  <div>
    <Header/>
    <SWRConfig value={config => ({ ...config, dedupingInterval: 1000 })}>
      <Main />
    </SWRConfig>
  </div>
</SWRConfig>

Where you can inherit the parent configuration and override the dedupingInterval value, but reuse the other options.

Breakings

SWRConfig.defaultSWRConfig.defaultValue (#2023)

This is a currently undocumented API, but planned to go stable with the 2.0 release. You can access to SWR’s default options via the SWRConfig.defaultValue static and read-only property.

What's Changed

New Contributors

Full Changelog: 2.0.0-beta.3...2.0.0-beta.4

Don't miss a new swr release

NewReleases is sending notifications on new releases.