All Projects → GoogleChromeLabs → React Adaptive Hooks

GoogleChromeLabs / React Adaptive Hooks

Licence: apache-2.0
Deliver experiences best suited to a user's device and network constraints

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to React Adaptive Hooks

vue-adaptive-utils
Deliver empathetic experiences to your users by adapting to their capabilities
Stars: ✭ 59 (-98.76%)
Mutual labels:  cpu, memory, loading, adaptive-loading
Walle
iOS Application performance monitoring
Stars: ✭ 19 (-99.6%)
Mutual labels:  cpu, memory, performance
Iglance
Free system monitor for OSX and macOS. See all system information at a glance in the menu bar.
Stars: ✭ 1,358 (-71.41%)
Mutual labels:  cpu, memory, network
Heim
Cross-platform async library for system information fetching 🦀
Stars: ✭ 572 (-87.96%)
Mutual labels:  cpu, memory, network
Easydeviceinfo
📱 [Android Library] Get device information in a super easy way.
Stars: ✭ 1,698 (-64.25%)
Mutual labels:  cpu, memory, network
cpu monitor
ROS node that publishes all nodes' CPU and memory usage
Stars: ✭ 52 (-98.91%)
Mutual labels:  cpu, memory
kotary
Managing Kubernetes Quota with confidence
Stars: ✭ 85 (-98.21%)
Mutual labels:  cpu, memory
stress
Single-purpose tools to stress resources
Stars: ✭ 24 (-99.49%)
Mutual labels:  cpu, memory
audria
audria - A Utility for Detailed Ressource Inspection of Applications
Stars: ✭ 35 (-99.26%)
Mutual labels:  cpu, memory
psutil
Cross-platform lib for process and system monitoring in Python
Stars: ✭ 8,488 (+78.69%)
Mutual labels:  cpu, memory
CPU-MEM-monitor
A simple script to log Linux CPU and memory usage (using top or pidstat command) over time and output an Excel- or OpenOfficeCalc-friendly report
Stars: ✭ 41 (-99.14%)
Mutual labels:  cpu, memory
doc
Get usage and health data about your Node.js process.
Stars: ✭ 17 (-99.64%)
Mutual labels:  cpu, memory
nodejs
Node.js in-process collectors for Instana
Stars: ✭ 66 (-98.61%)
Mutual labels:  cpu, memory
cpu-memory-monitor
CPU & Memory Monitor, auto dump.
Stars: ✭ 26 (-99.45%)
Mutual labels:  cpu, memory
hardware
Get CPU, Memory and Network informations of the running OS and its processes
Stars: ✭ 70 (-98.53%)
Mutual labels:  cpu, memory
Models
Model Zoo for Intel® Architecture: contains Intel optimizations for running deep learning workloads on Intel® Xeon® Scalable processors
Stars: ✭ 248 (-94.78%)
Mutual labels:  cpu, performance
Linux Network Performance Parameters
Learn where some of the network sysctl variables fit into the Linux/Kernel network flow
Stars: ✭ 3,112 (-34.48%)
Mutual labels:  network, performance
Mobileperf
Android performance test
Stars: ✭ 286 (-93.98%)
Mutual labels:  cpu, memory
Arch
极客时间专栏《许式伟的架构课》相关的源代码:冯诺伊曼结构
Stars: ✭ 335 (-92.95%)
Mutual labels:  cpu, memory
Stats
macOS system monitor in your menu bar
Stars: ✭ 7,134 (+50.19%)
Mutual labels:  cpu, network

React Adaptive Loading Hooks & Utilities · 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:

import { useNetworkStatus } from 'react-adaptive-hooks/network';
import { useSaveData } from 'react-adaptive-hooks/save-data';
import { useHardwareConcurrency } from 'react-adaptive-hooks/hardware-concurrency';
import { useMemoryStatus } from 'react-adaptive-hooks/memory';
import { useMediaCapabilitiesDecodingInfo } from 'react-adaptive-hooks/media-capabilities';

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)

import React from 'react';

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

const MyComponent = () => {
  const { effectiveConnectionType } = useNetworkStatus();

  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>;
};

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.

// Inside of a functional React component
const initialEffectiveConnectionType = '4g';
const { effectiveConnectionType } = useNetworkStatus(initialEffectiveConnectionType);

Save Data

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

import React from 'react';

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

const MyComponent = () => {
  const { saveData } = useSaveData();
  return (
    <div>
      { saveData ? <img src='...' /> : <video muted controls>...</video> }
    </div>
  );
};

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.

// Inside of a functional React component
const initialSaveData = true;
const { saveData } = useSaveData(initialSaveData);

CPU Cores / Hardware Concurrency

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

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>
  );
};

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)

import React from 'react';

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

const MyComponent = () => {
  const { deviceMemory } = useMemoryStatus();
  return (
    <div>
      { deviceMemory < 4 ? <img src='...' /> : <video muted controls>...</video> }
    </div>
  );
};

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.

// Inside of a functional React component
const initialMemoryStatus = { deviceMemory: 4 };
const { deviceMemory } = useMemoryStatus(initialMemoryStatus);

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.

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>
  );
};

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 optional initialMediaCapabilitiesInfo 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:

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:

import React from 'react';

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

export default Light;

Full.js:

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

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;

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

import {
  useNetworkStatus,
  useSaveData,
  useHardwareConcurrency,
  useMemoryStatus,
  useMediaCapabilitiesDecodingInfo
} from 'react-adaptive-hooks/dist/index.umd.js';

Browser Support

Demos

Network

Save Data

CPU Cores / Hardware Concurrency

Memory

Hybrid

References

License

Licensed under the Apache-2.0 license.

Team

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].