React Adaptive Loading Hooks

Deliver experiences best suited to a user's device and network constraints

README

React Adaptive Loading Hooks & Utilities · undefined Build Status npm bundle size


Deliver experiences best suited to a user's device and network constraints (experimental)


This is a suite of React Hooks and utilities for adaptive loading based on a user's:


It can be used to add patterns for adaptive resource loading, data-fetching, code-splitting and capability toggling.

Objective


Make it easier to target low-end devices while progressively adding high-end-only features on top. Using these hooks and utilities can help you give users a great experience best suited to their device and network constraints.

Installation


npm i react-adaptive-hooks --save or yarn add react-adaptive-hooks

Usage


You can import the hooks you wish to use as follows:

  1. ``` js
  2. import { useNetworkStatus } from 'react-adaptive-hooks/network';
  3. import { useSaveData } from 'react-adaptive-hooks/save-data';
  4. import { useHardwareConcurrency } from 'react-adaptive-hooks/hardware-concurrency';
  5. import { useMemoryStatus } from 'react-adaptive-hooks/memory';
  6. import { useMediaCapabilitiesDecodingInfo } from 'react-adaptive-hooks/media-capabilities';
  7. ```

and then use them in your components. Examples for each hook and utility can be found below:

Network


useNetworkStatus React hook for adapting based on network status (effective connection type)

  1. ``` js
  2. import React from 'react';

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

  4. const MyComponent = () => {
  5.   const { effectiveConnectionType } = useNetworkStatus();

  6.   let media;
  7.   switch(effectiveConnectionType) {
  8.     case 'slow-2g':
  9.       media = <img src='...' alt='low resolution' />;
  10.       break;
  11.     case '2g':
  12.       media = <img src='...' alt='medium resolution' />;
  13.       break;
  14.     case '3g':
  15.       media = <img src='...' alt='high resolution' />;
  16.       break;
  17.     case '4g':
  18.       media = <video muted controls>...</video>;
  19.       break;
  20.     default:
  21.       media = <video muted controls>...</video>;
  22.       break;
  23.   }
  24.   
  25.   return <div>{media}</div>;
  26. };
  27. ```

effectiveConnectionType values can be slow-2g, 2g, 3g, or 4g.

This hook accepts an optional initialEffectiveConnectionType string argument, which can be used to provide a effectiveConnectionType state value when the user's browser does not support the relevant NetworkInformation API. Passing an initial value can also prove useful for server-side rendering, where the developer can pass an ECT Client Hint to detect the effective network connection type.

  1. ``` js
  2. // Inside of a functional React component
  3. const initialEffectiveConnectionType = '4g';
  4. const { effectiveConnectionType } = useNetworkStatus(initialEffectiveConnectionType);
  5. ```

Save Data


useSaveData utility for adapting based on the user's browser Data Saver preferences.

  1. ``` js
  2. import React from 'react';

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

  4. const MyComponent = () => {
  5.   const { saveData } = useSaveData();
  6.   return (
  7.     <div>
  8.       { saveData ? <img src='...' /> :
  9.     </div>
  10.   );
  11. };
  12. ```

saveData values can be true or false.

This hook accepts an optional initialSaveData boolean argument, which can be used to provide a saveData state value when the user's browser does not support the relevant NetworkInformation API. Passing an initial value can also prove useful for server-side rendering, where the developer can pass a server Save-Data Client Hint that has been converted to a boolean to detect the user's data saving preference.

  1. ``` js
  2. // Inside of a functional React component
  3. const initialSaveData = true;
  4. const { saveData } = useSaveData(initialSaveData);
  5. ```

CPU Cores / Hardware Concurrency


useHardwareConcurrency utility for adapting to the number of logical CPU processor cores on the user's device.

  1. ``` js
  2. import React from 'react';

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

  4. const MyComponent = () => {
  5.   const { numberOfLogicalProcessors } = useHardwareConcurrency();
  6.   return (
  7.     <div>
  8.       { numberOfLogicalProcessors <= 4 ? <img src='...' /> :
  9.     </div>
  10.   );
  11. };
  12. ```

numberOfLogicalProcessors values can be the number of logical processors available to run threads on the user's device.

Memory


useMemoryStatus utility for adapting based on the user's device memory (RAM)

  1. ``` js
  2. import React from 'react';

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

  4. const MyComponent = () => {
  5.   const { deviceMemory } = useMemoryStatus();
  6.   return (
  7.     <div>
  8.       { deviceMemory < 4 ? <img src='...' /> :
  9.     </div>
  10.   );
  11. };
  12. ```

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 DeviceMemory API. 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.

  1. ``` js
  2. // Inside of a functional React component
  3. const initialMemoryStatus = { deviceMemory: 4 };
  4. const { deviceMemory } = useMemoryStatus(initialMemoryStatus);
  5. ```

Media Capabilities


useMediaCapabilitiesDecodingInfo utility for adapting based on the user's device media capabilities.

Use case: this hook can be used to check if we can play a certain content type. 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.

  1. ``` js
  2. import React from 'react';

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

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

  14. const initialMediaCapabilitiesInfo = { powerEfficient: true };

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

  17.   return (
  18.     <div>
  19.       <video src={mediaCapabilitiesInfo.supported ? videoSources.webm : videoSources.mp4} controls>...</video>
  20.     </div>
  21.   );
  22. };
  23. ```

mediaCapabilitiesInfo value contains the three Boolean properties supported, smooth, and powerEfficient, which describe whether decoding the media described would be supported, smooth, and powerEfficient.

This utility accepts a MediaDecodingConfiguration object argument and an optionalinitialMediaCapabilitiesInfo object argument, which can be used to provide a mediaCapabilitiesInfo state value when the user's browser does not support the relevant Media Capabilities API or no media configuration was given.

Adaptive Code-loading & Code-splitting


Code-loading


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:

  1. ``` js
  2. import React, { Suspense, lazy } from 'react';

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

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

  6. const MyComponent = () => {
  7.   const { effectiveConnectionType } = useNetworkStatus();
  8.   return (
  9.     <div>
  10.       <Suspense fallback={<div>Loading...</div>}>
  11.         { effectiveConnectionType === '4g' ? <Full /> : > }
  12.       </Suspense>
  13.     </div>
  14.   );
  15. };

  16. export default MyComponent;
  17. ```

Light.js:
  1. ``` js
  2. import React from 'react';

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

  6. export default Light;
  7. ```

Full.js:
  1. ``` js
  2. import React from 'react';
  3. import Magnifier from 'react-magnifier';

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

  7. export default Full;
  8. ```

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).

  1. ``` js
  2. import React, { Suspense } from 'react';

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

  5.   let module;
  6.   switch (effectiveType) {
  7.     case '3g':
  8.       module = import(/* webpackChunkName: "light" */ './Light.js');
  9.       break;
  10.     case '4g':
  11.       module = import(/* webpackChunkName: "full" */ './Full.js');
  12.       break;
  13.     default:
  14.       module = import(/* webpackChunkName: "full" */ './Full.js');
  15.       break;
  16.   }

  17.   return module;
  18. });

  19. const App = () => {
  20.   return (
  21.     <div className='App'>
  22.       <Suspense fallback={<div>Loading...</div>}>
  23.         <Component />
  24.       </Suspense>
  25.     </div>
  26.   );
  27. };

  28. export default App;
  29. ```

Server-side rendering support


The built version of this package uses ESM (native JS modules) by default, but is not supported on the server-side. When using this package in a web framework like Next.js with server-rendering, we recommend you

Transpile the package by installing next-transpile-modules. (example project). This is because Next.js currently does not passnode_modules into webpack server-side.

Use a UMD build as in the following code-snippet: (example project)
  1. ```
  2. import {
  3.   useNetworkStatus,
  4.   useSaveData,
  5.   useHardwareConcurrency,
  6.   useMemoryStatus,
  7.   useMediaCapabilitiesDecodingInfo
  8. } from 'react-adaptive-hooks/dist/index.umd.js';
  9. ```

Browser Support








Demos


Network


Network-aware loading with create-react-app (Live)
Network-aware code-splitting with create-react-app (Live)
Network-aware data-fetching with create-react-app (Live)


Save Data



CPU Cores / Hardware Concurrency



Memory


Memory considerate loading with create-react-app (Live)


Hybrid



References



License


Licensed under the Apache-2.0 license.

Team


This project is brought to you by Addy Osmani and Anton Karlovskiy.