We can use the state management tools provided by the React to use in the same data among components but the data has to be passed to the every components used in the apps through props. Use of useeffects and useState are great tool in this context.
With SWR, components will get a stream of data updates constantly and automatically and the UI will be always fast and reactive.
There will be situation where we want to pass data to components and update the UI. The only way achieve this is through a global store, may be Redux. lol
Vercel has built tool called SWR which will help us to store and retrieve data from API. With useSWR function we can fetch data and it will reuse the data through the app.
When user switch between tabs it automatically update the cache, so the UI too. This is not a store, but helps when we want to use API data. More over it's light weight and fast as Humming bird, lol.
How to setup
Install the dependency and create a fetcher function for API call.
yarn add swr
//fetcher.ts export default async function fetcher<JSON = any>( input: RequestInfo, init?: RequestInit ): Promise<JSON> { const res = await fetch(input, init) return res.json() }
The second step is to use the useSWR in your app
import useSWR from 'swr' .... const { data, error } = useSWR('http://localhost:3000/api/users?limit=10', fetcher) if (error) return <div>failed to load</div> if (!data) return <div>loading...</div>
For small apps SWR is enough. Official documentation will be helpful , if you want try SWR in the next React app.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.