SWR In React-Native Part1

Why use SWR?

SWR is caching strategy that is gaining popular in React and React-Native. It allow us to load cached data(stale), while at the same time refresh the content(revalidate) so that updated content is served in future. SWR reduces multiple times of page rendering.

SWR

SWR (stale-while-revalidate) is react hooks library for remote data fetching. This is the new way to retrieving data in React Application. Which makes things easier , Such as pagination,caching and so on. SWR working in three steps are,

  1. SWR firstly returns data from cache (stale).
  2. Call the web API request (revalidate).
  3. Finally comes with up-to-date again.

Feature

  1. Fast page navigation.
  2. Remove page re-rendering.
  3. Request de-duplication.
  4. Minimal API.
  5. pagination.
  6. Support to React Native

Difference Between Fetch and Axios

There is many way in React Application to make HTTP request. Two of them most popular is Fetch and Axios library. They both are very strong in fetching or sending data. Fetch and Axios will just send request and returns expected data. They do not help us to cache or paginate data.

As compared to SWR, it is different because the SWR under uses Fetch API to request data from server. So, SWR is very useful in cache, pagination, fetching etc. and precise a certain level of reactivity out of the box that doesn’t have to the Axios and Fetch.

It is big feature to help out React Application fast. SWR provides some enhancements to keep our app synchronized in back-end and increases performance of our Application. useSWR Medium Blog

Use of SWR

Fetching data from API using SWR hooks. Before that need to install SWR package in application.

yarn add swr

OR

npm install swr

"useSWR Installation"

After successfully installed package check in package.json . Now, start to fetch data from API using useSWR . However,there are two ways to configuration of SWR either locally or globally. In Local we create new file ,we have to setup SWR again to fetch remote data. But in Global setup allow us to reuse of SWR configuration. Because fetcher function is declared once and used in different files.Uses useSWR(key, fetcher, options) to fetch API data .

useSWR returns the following parameters

data : data for the given key resolved by the fetcher (undefined if not yet loaded) error : the error thrown by the fetcher isValidating : boolean representing whether there is a request or revalidation in progress mutate(data?, shouldRevalidate) : a function to mutate the cached data

"useSWR Code"

Let’s see the file structure in above image.Folder structure is very simple created new folder swrapi that holds Operator.js file.

import React from 'react'
import useSWR from 'swr'
import { View, Text, StyleSheet, FlatList } from 'react-native'

const operatorEndpoint =
  'https://run.mocky.io/v3/eb1d674a-f6fc-4d7a-837f-bd09bab735f7'
const getData = async () => {
  const response = await fetch(operatorEndpoint)
  return await response.json()
}

const Operator = () => {
  const { data, error } = useSWR('operator_key', getData)
  if (error)
    return (
      <View>
        <Text>failed to load</Text>
      </View>
    )
  if (!data)
    return (
      <View>
        <Text>loading...</Text>
      </View>
    )
  return (
    <View>
      <Text style={styles.flatList}>OPERATORS</Text>
      <View style={styles.mainView}>
        <FlatList
          data={data.operator}
          renderItem={({ item }) => (
            <View style={styles.mainView}>
              <Text style={styles.textStyle}>{item.name}</Text>
              <Text style={styles.codeText}>{item.code}</Text>
            </View>
          )}
        />
      </View>
      <Text style={styles.LabelText}>Developed By Consisty System</Text>
    </View>
  )
}
export default Operator

Now, we are started with importing useSWR from th SWR library. This is used to declare the URL of the API want o get data and fetch function to fetch those data. getData() function is declared to fetch remote data from API. Response is coming in JSON format. For Fetch function passes operatorEndpoint(URL) as parameter created by Designer Mocky. Which format data into JSON and returns it. With returned values, we can check data is successfully returned or not. Once return data successfully then loop through it. In Operator.js to show operator name and code value using FlatList it retrieve data . Using renderItem showing all item data and we can apply your own styles for that. With that in place, if you navigate to the root folder of the project and run on the terminal the following command:

Yarn start OR expo start

Or if using npm

npm start

"useSWR Example"

You should see that the data fetched successfully from Operator API and displayed as per your expectation. With SWR, components will get a stream of data updates constantly and automatically. Thus, the UI will be always fast and reactive.


Written by@Sandhya Deshmukh
Have a good experiance on Android in fintech, CRM domain. Also expert in React-Native, React