Each asset you create comes with its own cache. When you request something from it, the arguments that you pass will act as cache-keys. If you request later on using the same keys, it won't have to re-fetch but serves the result that it already knows.
import React, { Suspense } from "react"
import { createAsset } from "use-asset"
const asset = createAsset(async (id, version) => {
const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)
return await res.json()
})
function Post({ id }) {
const { by, title } = asset.read(id, "v0")
return <div>{title} by {by}</div>
}
function App() {
<Suspense fallback={null}>
<Post id={10000} />
</Suspense>
}
Preloading assets
asset.preload("/image.png")
Cache busting strategies
const asset = createAsset(promiseFn, 15000)
asset.clear()
asset.clear("/image.png")
Peeking into entries outside of suspense
asset.peek("/image.png")
You can also use the useAsset
hook, which is modelled after react-promise-suspense. This makes it possible to define assets on the spot instead of having to define them externally. They use a global cache, anything you request at any time is written into it.
import { useAsset } from "use-asset"
function Post({ id }) {
const { by, title } = useAsset(fn, id)
return <div>{title} by {by}</div>
}
function App() {
<Suspense fallback={null}>
<Post id={1000} />
Cache busting, preload and peeking
The hook has the same API as any asset:
useAsset.lifespan = 15000
useAsset(promiseFn, "/image.png")
useAsset.clear()
useAsset.clear("/image.png")
useAsset.preload(promiseFn, "/image.png")
useAsset.peek("/image.png")
Simple data fetching
Fetching posts from hacker-news: codesandbox
Infinite load on scroll
Fetching HN posts infinitely: codesandbox
Async dependencies
Component A waits for the result of component B: codesandbox