When React Hooks rolled out the other year, it was a big step towards making reactive user interfaces (UIs) and experiences easier. By using hooks, developers can separate logic and concerns a bit further and move more toward functional programming.
The team over at Next.js recently created a custom hook dubbed, useSWR
, which stands for stale-while-revalidate
. In the docs, SWR
updates components continuously and automatically. UIs will always be responsive and fast.
I've already used SWR in a project for user authentication and synchronizing a dashboard with an API data source. The team behind useSWR
has created documentation that makes learning to use it relatively easy. Here is a contrived, yet common example of getting started:
import useSWR from 'swr'; import { Container, Paragraph } from '@/components/system'; function Dashboard() { const { data: user, error: userError } = useSWR('/api/user', fetcher); const { data: dashboard, error: dashboardError } = useSWR( '/api/dashboard', fetcher ); if (userError || dashboardError) return <Container>failed to load</Container>; if (!user && !dashboard) return <Container>loading...</Container>; return ( <Container> <Paragraph>Hey there {user.name}!</Paragraph> </Container> //... render dashboard data ); }
Let's dig into our example code a bit.
- We have two
useSWR
hook instances, each returning two values:data
anderror
- The data will be
undefined
when the request (fetcher
) has not yet completed - When we get a
response
, it setsdata
anderror
based on theresult
of thefetcher
and re-renders the component - The
fetcher
can be any asynchronous function, so you can use your favorite data-fetching library to handle that part, likefetch
oraxios
- Once we have actual data, we can render it with our
Dasboard
component(s)
And, voilà
! We have a UI that is fast and efficient using the useSWR
hook.
Learn more about useSWR
at https://swr.now.sh.
Manny's an effective communicator and excels at unblocking individuals and connecting them with the resources needed to solve their problems.
Software Engineering @ Tesla