Optimizing UX: The Art of Adaptive Loading in Web Performance
Tags: webdev, webperf, frontend, react
Published: 2024-03-22 06:46:32

## Introduction
In today's time, becoming a web developer is not that easy as more and more challenges come hand in hand. You can't build one solution that will **work for all** the users. Today, we are going to discuss one such topic called **Adaptive Loading**.

In today's era, there are a lot of devices which render the webpage. They have different internet speeds, different processing power and whatnot. Our goal is always to provide the best experience to the user. We can use a package to serve different contents based on their device.

## Optimizing UX: react-adaptive-hooks
The package name is `react-adaptive-hooks`, developed by **Google Chrome Labs**. The main objective of this package is to make it easier to target **low-end devices** while **progressively adding high-end-only features** on top. 

We can do a lot of things with this package. Some of them are **checking the network status**, **checking save data preferences**, **checking CPU Cores** and whatnot. Using the hooks and utilities can help you give users a great experience best suited to their device and network constraints. 

## Installation
You can install the package using `npm` and `yarn`. 
For npm users, execute the following command in the terminal 
```bash
npm install react-adaptive-hooks
```

For yarn users, execute the following command in the terminal 
```bash
yarn add react-adaptive-hooks
```

## Network
There are a lot of use cases when we want to render different content based on the network connection type. For example, we can load a high-resolution image if the network connection is **4g**, but for **slow-2g**, we want to load a low-resolution image. To check the network status, we can use the `useNetworkStatus()` hook. We can also provide a fallback value if the user's device doesn't support the NewworkInformation API to get the data. 
```jsx
import React from 'react';

import { useNetworkStatus } from 'react-adaptive-hooks/network';

const MyComponent = () => {
  // used when unable to fetch the current network status
  const initialEffectiveConnectionType = '3g'; 
  const { effectiveConnectionType } = useNetworkStatus(initialEffectiveConnectionType);

  let media;
  switch(effectiveConnectionType) {
    case 'slow-2g':
      media = <img src='...' alt='low resolution' />;
      break;
    case '2g':
      media = <img src='...' alt='medium resolution' />;
      break;
    case '3g':
      media = <img src='...' alt='high resolution' />;
      break;
    case '4g':
      media = <video muted controls>...</video>;
      break;
    default:
      media = <video muted controls>...</video>;
      break;
  }
  
  return <div>{media}</div>;
};
```

## Save Data
There are situations when user opt in for save data preferences. We can render different content based on user's save data preferences. To check save data preferences, we can use the `useSaveData()` hook. Also, here we can pass a fallback value if NetworkInformationAPI is unable to fetch the browser's data.
```jsx
import React from 'react';

import { useSaveData } from 'react-adaptive-hooks/save-data';

const MyComponent = () => {
  // used when unable to fetch save data preference
  const initialSaveData = false;
  const { saveData } = useSaveData();
  return (
    <div>
      { saveData ? <img src='...' /> : <video muted controls>...</video> }
    </div>
  );
};
```

## Media Capabilities
This hook is useful for browser support use cases. For example, Safari does not support **WebM** so we want to fallback to **MP4** but if Safari at some point does support **WebM** it will automatically load WebM videos.

```jsx
import React from 'react';

import { useMediaCapabilitiesDecodingInfo } from 'react-adaptive-hooks/media-capabilities';

const webmMediaDecodingConfig = {
  type: 'file', // 'record', 'transmission', or 'media-source'
  video: {
    contentType: 'video/webm;codecs=vp8', // valid content type
    width: 800, // width of the video
    height: 600, // height of the video
    bitrate: 10000, // number of bits used to encode 1s of video
    framerate: 30 // number of frames making up that 1s.
  }
};

const initialMediaCapabilitiesInfo = { powerEfficient: true };

const MyComponent = ({ videoSources }) => {
  const { mediaCapabilitiesInfo } = useMediaCapabilitiesDecodingInfo(webmMediaDecodingConfig, initialMediaCapabilitiesInfo);

  return (
    <div>
      <video src={mediaCapabilitiesInfo.supported ? videoSources.webm : videoSources.mp4} controls>...</video>
    </div>
  );
};
```

## CPU Cores / Hardware Concurrency
We can also load the content based on the logical CPU processor cores on user device. So for devices with lower CPU cores, we can avoid loading heavy contents.
```jsx
import React from 'react';

import { useHardwareConcurrency } from 'react-adaptive-hooks/hardware-concurrency';

const MyComponent = () => {
  const { numberOfLogicalProcessors } = useHardwareConcurrency();
  return (
    <div>
      { numberOfLogicalProcessors <= 4 ? <img src='...' /> : <video muted controls>...</video> }
    </div>
  );
};
```
## Memory
To render content based on memory we use the `useMemoryStatus()` hook. This hook returns an object to us which contains a `deviceMemory` key. `deviceMemory` values can be the approximate amount of device memory in gigabytes. 
This hook accepts an optional `initialMemoryStatus` object argument, which can be used to provide a `deviceMemory` state value when the user's browser does not support the relevant DeviceMemoryAPI. Passing an initial value can also prove useful for **server-side rendering**, where the developer can pass a server **Device-Memory Client Hint** to detect the memory capacity of the user's device.

```jsx
import React from 'react';

import { useMemoryStatus } from 'react-adaptive-hooks/memory';

const MyComponent = () => {
  // used when DeviceMemoryAPI is unable to fetch the memory data
  const initialMemoryStatus = { deviceMemory: 4 };
  const { deviceMemory } = useMemoryStatus(initialMemoryStatus);
  return (
    <div>
      { deviceMemory < 4 ? <img src='...' /> : <video muted controls>...</video> }
    </div>
  );
};
```

## Adaptive Code-loading & Code-splitting
### Code Loading:
We can also load a separate component also based on the network status. We can deliver a light, interactive core experience to users and progressively add high-end-only features on top, if a user's hardware can handle it. Below is an example using the Network Status hook:
```jsx
import React, { Suspense, lazy } from 'react';

import { useNetworkStatus } from 'react-adaptive-hooks/network';

const Full = lazy(() => import(/* webpackChunkName: "full" */ './Full.js'));
const Light = lazy(() => import(/* webpackChunkName: "light" */ './Light.js'));

const MyComponent = () => {
  const { effectiveConnectionType } = useNetworkStatus();
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        { effectiveConnectionType === '4g' ? <Full /> : <Light /> }
      </Suspense>
    </div>
  );
};

export default MyComponent;
```
Light.js:
```jsx
import React from 'react';

const Light = ({ imageUrl, ...rest }) => (
  <img src={imageUrl} {...rest} />
);

export default Light;
```
Full.js:
```jsx
import React from 'react';
import Magnifier from 'react-magnifier';

const Full = ({ imageUrl, ...rest }) => (
  <Magnifier src={imageUrl} {...rest} />
);

export default Full;
```
### Code-splitting:
We can extend `React.lazy()` by incorporating a check for a device or network signal. Below is an example of network-aware code-splitting. This allows us to conditionally load a light core experience or full-fat experience depending on the user's effective connection speed (via navigator.connection.effectiveType API).
```jsx 
import React, { Suspense } from 'react';

const Component = React.lazy(() => {
  const effectiveType = navigator.connection ? navigator.connection.effectiveType : null

  let module;
  switch (effectiveType) {
    case '3g':
      module = import(/* webpackChunkName: "light" */ './Light.js');
      break;
    case '4g':
      module = import(/* webpackChunkName: "full" */ './Full.js');
      break;
    default:
      module = import(/* webpackChunkName: "full" */ './Full.js');
      break;
  }

  return module;
});

const App = () => {
  return (
    <div className='App'>
      <Suspense fallback={<div>Loading...</div>}>
        <Component />
      </Suspense>
    </div>
  );
};

export default App;
```
## Conclusion
Adaptive Loading is one of the amazing techniques that we can use to built a better web experience for everyone. But, this API is still not supported for some of the browsers yet. For chromium based browsers like Chrome, Edge it is supported. So, always provide the fallback values so that it will prevent your code from getting errors. Thanks for reading the blog. If you like this blog and want to learn more Software Engineering topics, you can follow me on [LinkedIn](https://www.linkedin.com/in/debajit-mallick/) and [Twitter](https://twitter.com/mallickdebajit).