Skip to main content

How we implemented SWR in a project and why we loved it

Kamil Polok

Kamil Polok

Jun 09, 2021・6 min read

Next.jsReact

Why SWR?

Recently, we had the opportunity at SDH to develop a project using React with support from Redux/Toolkit. Thing is, though data was kept and fetched in the store, there was no caching mechanism implemented in the app.  And holding dozens of responses in the state is not my idea of a cool idea. Whatever the case, it soon got a little too easy to get lost in all those state slices, despite the use of Toolkit.  

What’s more, it had zero influence on the backend at that point. With those iceberg-sized chunks of data drifting about, some requests took an eternity to resolve.  And since the UI’s application consisted of long item lists with few CRUD operations,  it soon became clear that some form of cache would come in pretty handy just about then. So the choice fell to SWR - a library made by the developers of Vercel (also of Next.js fame).

What is SWR?

Ok, do you like reading definitions? I hope not, because this is going to be one of the shortest you've ever read. ‘SWR is a React Hooks library for remote data fetching’. That's it. Simple? Yes, but I will now show you that SWR is also very powerful. And in case you were wondering, SWR stands for stale-while-revalidate. Which already explains how it works. SWR returns data from cache (stale), sends a fetch request to get updated data (revalidate), then returns new data.  Like I said, simple. 


Why we loved SWR

It’s easy to recognise how using SWR eliminates problems described at the beginning of this article. Thanks to SWR, we:

  • Made the UI work perfectly (after initial data requests) thanks to caching data 
  • Removed nearly all slices holding API data and accompanying logic
  • Simplified the flow of revalidating data after making CRUD operations on data collections
  • Sped up the development of new API-dependent features

How did we actually implement this library for such magical results? 

How SWR works

After a short while of working with SWR, it proved itself to be rather simple and quite user-friendly. Fancy making an API request using SWR? Have this:

Screenshot 2023-07-21 at 16.32.34.png

The only catch is the fetcher. It’s just your custom function for fetching data. The application we worked on already had axios set up and running with its entire config (interceptors, headers, base URL, etc.), so we just wrapped our axios instance like this to get our own custom fetcher:

Screenshot 2023-07-21 at 16.32.42.png

Therefore, the entire hook could look as simple as this (let's skip error handling in this example):

Screenshot 2023-07-21 at 16.32.48.png

And... that's it! We’ve created a hook for fetching API data using all the SWR goodies. Whenever this hook is fired, it will return previously fetched data first (if present), and only then revalidate data and return new collection afterwards.

SWR out of the box comes with a handful of pre-configured parameters (all are listed here), which make working with it a piece of cake. A favorite option worth mentioning is dedupingInterval.

Typical use-case scenario: fetch data in one component, keep developing this component further, watch children grow out of control, only for a 4th level child to need the data. How you get this data into the child component without much effort whilst avoiding repeated requests is always a challenge. But fear not: simply reuse the SWR hook... The deduping interval will not allow the request to be made again within a specified amount of time (2 seconds by default). Fair enough.

"But if I call the endpoint, and it returns the same data as before, my component will still re-render". It will not: SWR implements deep comparison so re-render will only be triggered when data has actually changed. And the comparison function can, of course, be customized. 

Data mutation

But you might argue that GETting data is always easy - what about the mutating part? Surely this is more complicated. Well, not really, mutations don't have to be a nightmare, and I was surprised how easy it is to mutate data using SWR (previously having had some fun with Apollo). Here's a real-life example:

Screenshot 2023-07-21 at 16.32.54.png

In this example mutate is a function imported from SWR and /users is the key we gave it in useUsers hook (It doesn't have to be the endpoint URL - you can pass the key and URL separately).

Should you wish to cache and update a single entity (object) fetched from a bigger collection, simply mutate it by its key like so:

Screenshot 2023-07-21 at 16.33.01.png

Looks too simple? It is simple. Try it for yourself and you just may save considerable time writing extensive Redux logic and debugging your API calls.

SWR integrations

As you can see, implementing SWR is simple; with a few nice touches,  it doesn’t take much to advance the above examples to higher, more abstract levels. Obviously, SWR is not limited to this and there is a great number of options and integrations available:

graphQL integration

error handling with retry options

auto revalidation

pagination support (also for infinite loading)

data prefetching

and many more (documentation)

We found working with SWR supremely cool and will definitely consider using it for future projects. If you’d like to learn more about this awesome library, visit their official website with documentation, configs and examples here.

Happy coding!

Unicorn3.png

 

Published on June 09, 2021

Share

Published on June 09, 2021


Kamil PolokKamil PolokFront-end developer Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Digital Transformation Strategy for Siemens Finance

Cloud-based platform for Siemens Financial Services in Poland

See full Case Study
Ad image
How we implemented SWR in a project and why we loved it
Don't miss a beat - subscribe to our newsletter
I agree to receive marketing communication from Startup House. Click for the details

You may also like...

How to generate PDF from HTML in React / Node.js app
ReactNode.js

How to generate PDF from HTML in React / Node.js app

Generating PDFs from HTML can be a challenge, but with the right methods, you can achieve the desired results. Explore different solutions, from using CSS print rules to libraries like html2canvas, jsPDF, and Puppeteer. Understand the pros and cons of each approach to find the best solution for your project. Contact us at hello@start-up.house for more information and assistance. Good luck in your PDF generation endeavors!

Eugene Zolotarenko

Eugene Zolotarenko

May 20, 2021・6 min read

4 reasons to use Chakra UI in your next project
Chakra UIReact

4 reasons to use Chakra UI in your next project

Chakra UI is a simple, modular, and accessible component library for building React apps with speed. With its easy customization, dark mode support, responsive design capabilities, and focus on accessibility, Chakra UI stands out among other UI libraries, making it an excellent choice for React developers.

Mateusz Wójcik

Mateusz Wójcik

Jan 19, 2021・4 min read

An industrial technician reviewing predictive maintenance alerts with vibration and thermal sensor data on a plant floor
AI AgentsPredictive MaintenanceIndustry 4.0

AI Agents for Predictive Maintenance and Asset Reliability

How autonomous agents read vibration, thermal and acoustic data to predict failures weeks ahead — and act on them without waiting for a human.

Alexander Stasiak

Alexander Stasiak

Aug 29, 2026・9 min read

Executives reviewing business intelligence dashboards and analytics visualisations together
Business OptimizationData Analysis Data Strategy

Business Intelligence Services & Solutions

Most organisations have more data than insight, and the gap is architectural rather than analytical. This guide explains how business intelligence services and solutions turn fragmented data into a strategic asset, and how modern BI differs from traditional reporting. It reviews industry-specific applications, provides a step-by-step implementation framework, and names the pitfalls that stall BI projects. The final sections cover AI-augmented analytics and how to future-proof a data strategy.

Alexander Stasiak

Alexander Stasiak

Jul 15, 2026・8 min read

A cluttered digital workspace showing outdated documentation files, broken links, and stale content warnings on a knowledge base dashboard
SaaSUX design

Why Knowledge Base Content Becomes Outdated

Your knowledge base was a source of truth once. Now it's a liability. Products have changed, teams have restructured, and the documentation your employees and customers rely on is silently giving wrong answers.

Alexander Stasiak

Alexander Stasiak

Mar 17, 2026・11 min read

A factory operations dashboard showing live workflow status, bottleneck alerts and automated resource reallocation
AI AgentsAI in ManufacturingIndustry 4.0

AI Agents for Factory Workflow Optimization

How autonomous agents orchestrate the whole factory — resolving bottlenecks, scheduling maintenance and reallocating resources before output suffers.

Alexander Stasiak

Alexander Stasiak

Sep 28, 2026・8 min read

Recently added

Glass paper airplane flying through a chrome ring, symbolizing a fast, automated leasing application
FinTechAutomationCase Study

How Startup House Cut Leasing Applications to 2 Minutes for Siemens Financial Services

Leasing used to mean paperwork, manual credit checks, and decisions that waited for office hours. For Siemens Financial Services Poland, Startup House replaced that with SimplyLease Online: an application customers complete in about 2 minutes and an automated credit decision delivered in about 7, at any hour. This case study shows how the platform was built within Siemens Group security standards, how it connects to Siemens systems and external data providers, and what a partnership running since 2016 has delivered. It closes with three lessons that apply to almost any financing or lending product.

Alexander Stasiak

Alexander Stasiak

Oct 06, 2026・5 min read

Glass shield of four stacked layers with a glowing green core, symbolizing an AI agent embedded in a cybersecurity platform
AI AgentsCybersecurityCase Study

How a Cybersecurity Platform Serving Fortune 500 Clients Cut Onboarding by 95% with an AI Agent Built by Startup House

A cyber risk platform trusted by Fortune 500 companies had a familiar problem: customers respected it but opened it once a quarter, and onboarding took 45 minutes of guided setup. Startup House built Aria, an AI agent embedded inside the product, with a four-layer interface that serves board members, CFOs, and CISOs in one panel. Onboarding dropped by 95% to under 2 minutes, data exploration became fully self-serve, and the platform turned into a daily decision-support tool. This case study explains the interface, the tenant-isolation architecture, and why none of it required touching the platform's core codebase.

Marek Pałys

Marek Pałys

Oct 05, 2026・5 min read

Five glass measuring cylinders filled with violet and green liquid to different levels, symbolizing measurable project outcomes
Business OutcomesCase StudyAI Projects

AI and Digital Projects by Startup House: 5 Measurable Outcomes in Numbers

Claims are easy in software development, so this article sticks to numbers. It walks through five outcomes from Startup House client projects, from a 95% cut in onboarding time with an embedded AI agent to a 40% reduction in development costs for Omnipack. Each section says what kind of work produced the number and links to the public case study behind it. The closing section names three patterns these projects share, worth borrowing whether or not you work with us.

Alexander Stasiak

Alexander Stasiak

Oct 04, 2026・5 min read

Glass medical capsule inside a protective glass sphere with a chrome ring, symbolizing compliance-first healthcare software
HealthtechHIPAA ComplianceAI in healthcare

Healthtech Software Development at Startup House: Compliance-First Projects and Results

In healthcare software, compliance is either an architecture decision or a retrofit. This article shows what designing it in from day one looks like across three Startup House projects: a sales platform for Siemens Healthineers active in more than 60 countries, a dementia care MVP shaped by 7 user testing sessions with patients and caregivers, and Doogie, a HIPAA-grade AI showcase built in 2 months. It also explains how RAG keeps clinical AI answers traceable to verified sources, and why patient data is never used to train models. For MedTech companies and health SaaS platforms, it is a practical look at what compliance-first engineering means beyond the label.

Marek Pałys

Marek Pałys

Oct 03, 2026・5 min read

Two projects, one method: how phased delivery and real user testing took Graspify to live corporate training and gave LITTLEWINE an investor-ready scope.
Edtech transformationProduct discoveryAI In Education

Edtech Development at Startup House: What We've Built and What It Changed

EdTech platforms fail for UX reasons more often than technical ones: learners drop off, content doesn't scale, and ROI stays invisible. This article shows how Startup House avoids that with phased delivery and real user testing, using two projects as proof. Graspify went from a bold idea to a microlearning platform that trained hundreds of employees during a corporate event, and LITTLEWINE got an investor-ready scope from 10 user interviews in 2 weeks. It also covers AI learning tools that answer only from approved content and can go live in as little as 2 weeks.

Alexander Stasiak

Alexander Stasiak

Oct 02, 2026・5 min read

Glass and chrome balance scale holding green glass coins and a chrome padlock, symbolizing speed and control in fintech AI
FinTechAI in FinanceRegulatory Compliance

AI in Fintech: Startup House Projects, Lessons, and Outcomes

Fintech customers expect consumer-grade speed, while regulators expect bank-grade control. This article shows how Startup House has handled that tension in three projects: automated 24/7 credit decisions for Siemens Financial Services, a cyber risk platform that grew revenue 150% in a year, and a climate fintech team for CHOOOSE assembled in 2 weeks. Each project comes with the lesson it taught us. The article closes with five rules for AI in finance, from grounding every answer in verified data to designing tenant isolation into the architecture.

Marek Pałys

Marek Pałys

Oct 01, 2026・5 min read

Ready to centralize your know-how with AI?

Start a new chapter in knowledge management—where the AI Assistant becomes the central pillar of your digital support experience.

Work with a team trusted by top-tier companies.

Siemens logo
PwC logo
Toyota logo