7 reasons why you should use SWR
SWR is a React Hooks library for remote data fetching. The name “**SWR**” is derived from `stale-while-revalidate`, a cache invalidation strategy popularized by HTTP RFC 5861. **SWR** first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.
Why should you use SWR?
Let's see what problems SWR solves.
Auto Revalidation: Suppose, you have opened up you todo application on two tabs. Normally, In one tab if you add a new todo then you won't see the update on the other tab. SWR really solves this problem out of the box by auto re-validating. When you change your focus from the tab and then refocus again, swr will make sure the data is valid or up to date. This done through sending another request to the API.
Data Mutation: You can tell swr to re-validate your data with mutation. This is a example from SWR documentation. It shows how to automatically refetch the login info (e.g. inside
<Profile/>
) when the user clicks the “Logout” button.
import useSWR, { mutate } from 'swr'function App () {return (<div><Profile /><button onClick={() => {// set the cookie as expireddocument.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'// tell all SWRs with this key to revalidatemutate('/api/user')}}>Logout</button></div>)}
Real time experience: Suppose you want to create a todo app where you want to add new todo. But every time you add new item you have to refresh the page to see the changes. But with SWR
mutation
you can mutate the request. It simply means, when you add new data, it will automatically fetch another request and will update the ui.Request deduplication: Take a look at this code.
function useUser() {return useSWR('/api/user', fetcher)}function Avatar() {const { data, error } = useUser()if (error) return <Error />if (!data) return <Spinner />return <img src={data.avatar_url} />}function App() {return (<><Avatar /><Avatar /><Avatar /><Avatar /><Avatar /></>)}
Normally it will send same 3 request to the API. That is totally unnecessary. It will take more data and will cause unneccessary rendering. Swr solves this by request deduplication. It will only send one request because they are requested at the same time. The default de-duplicating interval is 2 seconds. But you can change from the config. So it won't cause unnecessary rendering or take more data. It makes our user experience better specifically for mobile devices.
Can be use with Both rest and graphql: SWR does not fetch the data. The fetcher function does. And that's allow us to use both REST and Graphql api.
Built-in caching support: When you first fetch data from an api endpoint it caches the response data. If you send a request to the same api then it will first give you the cached data while fetching the up to date data. So that you don't have to show loading state to the user.
Reusable code: SWR is itself a hook. And you can create custom hook from hooks. It allow us to write DRY(don't repeat yourself) code. Suppose you want to fetch data from /users
endpoint. So every time you want to fetch the data, you have to pass the fetcher function and options again and again. But if you create a custom hook then you don't have to pass anything again.
function App() {const { data, error, isValidating } = useSWR('/users', fetcher)return <>.... </>}// insteadfunction useUser() {return useSWR('/users', fetcher)}function App() {const { data, error, isValidating } = useUser()return <>.... </>}
- Super flexible: You can configure every settings of SWR if you want. You can also set a global configuration. Read more from swr options
And these are the problems that SWR solves. I also some other features.
- Built in Typescript support.
- Fast, lightweight.
- Tree shaking available.
These are the reasons why I love SWR and you should try it too.
Shameless Plug
I have made few project based videos with vanilla HTML, CSS, and JavaScript.
You will learn about:
- Javascript intersection observer to add cool effects
- DOM manipulation
- Aligning elements with CSS positions.
- How to make responsive websites.
- How to create slide based webpage.
These will be great projects to brush up on your front end skills.
If you are interested you can check the videos.
You can also demo the application from here:
Please like and subscribe to Cules Coding. It motivates me to create more content like this.
That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.
By the way, I am looking for a new opportunity in a company where I can provide great value with my skills. If you are a recruiter, looking for someone skilled in full stack web development and passionate about revolutionizing the world, feel free to contact me. Also, I am open to talking about any freelance project.
About me
Why do I do what I do?
The Internet has revolutionized our life. I want to make the internet more beautiful and useful.
What do I do?
I ended up being a full-stack software engineer.
What can I do?
I can develop complex full-stack web applications like social media applications or e-commerce sites. See more of my work from here
What have I done?
I have developed a social media application called Confession. The goal of this application is to help people overcome their imposter syndrome by sharing our failure stories.
Screenshot
I also love to share my knowledge. So, I run a youtube channel called Cules Coding where I teach people full-stack web development, data structure algorithms, and many more. So, Subscribe to Cules Coding so that you don't miss the cool stuff.
Want to work with me?
I am looking for a team where I can show my ambition and passion and produce great value for them. Contact me through my email or any social media as @thatanjan. I would be happy to have a touch with you.
Contacts
- Email: thatanjan@gmail.com
- linkedin: @thatanjan
- portfolio: anjan
- Github: @thatanjan
- Instagram (personal): @thatanjan
- Instagram (youtube channel): @thatanjan
- twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: