├── .travis.yml ├── index.js ├── .gitignore ├── babel.config.js ├── hardware-concurrency ├── index.js └── hardware-concurrency.test.js ├── package.json ├── save-data ├── index.js └── save-data.test.js ├── CONTRIBUTING.md ├── media-capabilities ├── index.js └── media-capabilities.test.js ├── memory ├── index.js └── memory.test.js ├── network ├── index.js └── network.test.js ├── LICENSE └── README.md /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - node 4 | branches: 5 | only: 6 | - master 7 | cache: 8 | npm: true 9 | directories: 10 | - node_modules 11 | notifications: 12 | email: false 13 | install: 14 | - npm ci 15 | script: npm run test 16 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | export { useNetworkStatus } from './network'; 2 | export { useSaveData } from './save-data'; 3 | export { useMemoryStatus } from './memory'; 4 | export { useHardwareConcurrency } from './hardware-concurrency'; 5 | export { useMediaCapabilitiesDecodingInfo } from './media-capabilities'; 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | /dist 14 | 15 | # misc 16 | .DS_Store 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | module.exports = { 18 | presets: [ 19 | "@babel/preset-env" 20 | ] 21 | }; 22 | -------------------------------------------------------------------------------- /hardware-concurrency/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | let initialHardwareConcurrency; 18 | if (typeof navigator !== 'undefined' && 'hardwareConcurrency' in navigator) { 19 | initialHardwareConcurrency = { 20 | unsupported: false, 21 | numberOfLogicalProcessors: navigator.hardwareConcurrency 22 | }; 23 | } else { 24 | initialHardwareConcurrency = { unsupported: true }; 25 | } 26 | const useHardwareConcurrency = () => { 27 | return { ...initialHardwareConcurrency }; 28 | }; 29 | 30 | export { useHardwareConcurrency }; 31 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-adaptive-hooks", 3 | "version": "0.1.0", 4 | "description": "Give users a great experience best suited to their device and network constraints", 5 | "repository": "https://github.com/GoogleChromeLabs/react-adaptive-hooks", 6 | "author": "Google Chrome", 7 | "license": "Apache-2.0", 8 | "private": false, 9 | "main": "dist/index.js", 10 | "module": "dist/index.module.js", 11 | "unpkg": "dist/index.umd.js", 12 | "source": "index.js", 13 | "scripts": { 14 | "build": "microbundle", 15 | "dev": "microbundle watch", 16 | "prepare": "npm run build", 17 | "test": "jest", 18 | "test:coverage": "jest --coverage" 19 | }, 20 | "peerDependencies": { 21 | "react": "^16.8.0 || ^17.0.0" 22 | }, 23 | "devDependencies": { 24 | "@babel/preset-env": "^7.5.5", 25 | "@testing-library/react-hooks": "^1.1.0", 26 | "babel-polyfill": "^6.26.0", 27 | "jest": "^24.8.0", 28 | "microbundle": "0.11.0", 29 | "react": "17.0.1", 30 | "react-test-renderer": "17.0.1" 31 | }, 32 | "keywords": [ 33 | "react-hooks", 34 | "hooks", 35 | "react", 36 | "performance" 37 | ] 38 | } 39 | -------------------------------------------------------------------------------- /save-data/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | let unsupported; 18 | 19 | const useSaveData = (initialSaveData = null) => { 20 | if (typeof navigator !== 'undefined' && 'connection' in navigator && 'saveData' in navigator.connection) { 21 | unsupported = false; 22 | } else { 23 | unsupported = true; 24 | } 25 | 26 | return { 27 | unsupported, 28 | saveData: unsupported 29 | ? initialSaveData 30 | : navigator.connection.saveData === true 31 | }; 32 | }; 33 | 34 | export { useSaveData }; 35 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution; 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /media-capabilities/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { useState, useEffect } from 'react'; 18 | 19 | const useMediaCapabilitiesDecodingInfo = (mediaDecodingConfig, initialMediaCapabilitiesInfo = {}) => { 20 | const supported = typeof navigator !== 'undefined' && 'mediaCapabilities' in navigator; 21 | const [mediaCapabilitiesInfo, setMediaCapabilitiesInfo] = useState(initialMediaCapabilitiesInfo); 22 | 23 | useEffect(() => { 24 | supported && 25 | navigator 26 | .mediaCapabilities 27 | .decodingInfo(mediaDecodingConfig) 28 | .then(setMediaCapabilitiesInfo) 29 | .catch(error => console.error(error)); 30 | }, [mediaDecodingConfig]); 31 | 32 | return { supported, mediaCapabilitiesInfo }; 33 | }; 34 | 35 | export { useMediaCapabilitiesDecodingInfo }; 36 | -------------------------------------------------------------------------------- /memory/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | let unsupported; 18 | if (typeof navigator !== 'undefined' && 'deviceMemory' in navigator) { 19 | unsupported = false; 20 | } else { 21 | unsupported = true; 22 | } 23 | let memoryStatus; 24 | if (!unsupported) { 25 | const performanceMemory = 'memory' in performance ? performance.memory : null; 26 | memoryStatus = { 27 | unsupported, 28 | deviceMemory: navigator.deviceMemory, 29 | totalJSHeapSize: performanceMemory 30 | ? performanceMemory.totalJSHeapSize 31 | : null, 32 | usedJSHeapSize: performanceMemory ? performanceMemory.usedJSHeapSize : null, 33 | jsHeapSizeLimit: performanceMemory 34 | ? performanceMemory.jsHeapSizeLimit 35 | : null 36 | }; 37 | } else { 38 | memoryStatus = { unsupported }; 39 | } 40 | 41 | const useMemoryStatus = initialMemoryStatus => { 42 | return unsupported && initialMemoryStatus 43 | ? { ...memoryStatus, ...initialMemoryStatus } 44 | : { ...memoryStatus }; 45 | }; 46 | 47 | export { useMemoryStatus }; 48 | -------------------------------------------------------------------------------- /network/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { useState, useEffect } from 'react'; 18 | 19 | let unsupported; 20 | 21 | const useNetworkStatus = initialEffectiveConnectionType => { 22 | if (typeof navigator !== 'undefined' && 'connection' in navigator && 'effectiveType' in navigator.connection) { 23 | unsupported = false; 24 | } else { 25 | unsupported = true; 26 | } 27 | 28 | const initialNetworkStatus = { 29 | unsupported, 30 | effectiveConnectionType: unsupported 31 | ? initialEffectiveConnectionType 32 | : navigator.connection.effectiveType 33 | }; 34 | 35 | const [networkStatus, setNetworkStatus] = useState(initialNetworkStatus); 36 | 37 | useEffect(() => { 38 | if (!unsupported) { 39 | const navigatorConnection = navigator.connection; 40 | const updateECTStatus = () => { 41 | setNetworkStatus({ 42 | effectiveConnectionType: navigatorConnection.effectiveType 43 | }); 44 | }; 45 | navigatorConnection.addEventListener('change', updateECTStatus); 46 | return () => { 47 | navigatorConnection.removeEventListener('change', updateECTStatus); 48 | }; 49 | } 50 | }, []); 51 | 52 | return { ...networkStatus, setNetworkStatus }; 53 | }; 54 | 55 | export { useNetworkStatus }; 56 | -------------------------------------------------------------------------------- /hardware-concurrency/hardware-concurrency.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { renderHook } from '@testing-library/react-hooks'; 18 | 19 | afterEach(function() { 20 | // Reload hook for every test 21 | jest.resetModules(); 22 | }); 23 | 24 | describe('useHardwareConcurrency', () => { 25 | const navigator = window.navigator; 26 | 27 | afterEach(() => { 28 | if (!window.navigator) window.navigator = navigator; 29 | }); 30 | 31 | test(`should return "true" for unsupported case`, () => { 32 | Object.defineProperty(window, 'navigator', { 33 | value: undefined, 34 | configurable: true, 35 | writable: true 36 | }); 37 | 38 | const { useHardwareConcurrency } = require('./'); 39 | const { result } = renderHook(() => useHardwareConcurrency()); 40 | 41 | expect(result.current.unsupported).toBe(true); 42 | }); 43 | 44 | test(`should return window.navigator.hardwareConcurrency`, () => { 45 | const { useHardwareConcurrency } = require('./'); 46 | const { result } = renderHook(() => useHardwareConcurrency()); 47 | 48 | expect(result.current.numberOfLogicalProcessors).toBe( 49 | window.navigator.hardwareConcurrency 50 | ); 51 | expect(result.current.unsupported).toBe(false); 52 | }); 53 | 54 | test('should return 4 for device of hardwareConcurrency = 4', () => { 55 | Object.defineProperty(window.navigator, 'hardwareConcurrency', { 56 | value: 4, 57 | configurable: true, 58 | writable: true 59 | }); 60 | const { useHardwareConcurrency } = require('./'); 61 | const { result } = renderHook(() => useHardwareConcurrency()); 62 | 63 | expect(result.current.numberOfLogicalProcessors).toEqual(4); 64 | expect(result.current.unsupported).toBe(false); 65 | }); 66 | 67 | test('should return 2 for device of hardwareConcurrency = 2', () => { 68 | Object.defineProperty(window.navigator, 'hardwareConcurrency', { 69 | value: 2, 70 | configurable: true, 71 | writable: true 72 | }); 73 | const { useHardwareConcurrency } = require('./'); 74 | const { result } = renderHook(() => useHardwareConcurrency()); 75 | 76 | expect(result.current.numberOfLogicalProcessors).toEqual(2); 77 | expect(result.current.unsupported).toBe(false); 78 | }); 79 | }); 80 | -------------------------------------------------------------------------------- /save-data/save-data.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { renderHook, act } from '@testing-library/react-hooks'; 18 | 19 | afterEach(function() { 20 | // Reload hook for every test 21 | jest.resetModules(); 22 | }); 23 | 24 | describe('useSaveData', () => { 25 | test(`should return "true" for unsupported case`, () => { 26 | const { useSaveData } = require('./'); 27 | const { result } = renderHook(() => useSaveData()); 28 | 29 | expect(result.current.unsupported).toBe(true); 30 | expect(result.current.saveData).toEqual(null); 31 | }); 32 | 33 | test('should return initialSaveData for unsupported case', () => { 34 | const initialSaveData = true; 35 | const { useSaveData } = require('./'); 36 | const { result } = renderHook(() => useSaveData(initialSaveData)); 37 | 38 | expect(result.current.unsupported).toBe(true); 39 | expect(result.current.saveData).toBe(initialSaveData); 40 | }); 41 | 42 | test(`should return "true" for enabled save data`, () => { 43 | global.navigator.connection = { 44 | saveData: true 45 | }; 46 | const { useSaveData } = require('./'); 47 | const { result } = renderHook(() => useSaveData()); 48 | 49 | expect(result.current.unsupported).toBe(false); 50 | expect(result.current.saveData).toEqual(navigator.connection.saveData); 51 | }); 52 | 53 | test(`should return "false" for disabled save data`, () => { 54 | global.navigator.connection = { 55 | saveData: false 56 | }; 57 | const { useSaveData } = require('./'); 58 | const { result } = renderHook(() => useSaveData()); 59 | 60 | expect(result.current.unsupported).toBe(false); 61 | expect(result.current.saveData).toEqual(navigator.connection.saveData); 62 | }); 63 | 64 | test('should not return initialSaveData for supported case', () => { 65 | const initialSaveData = false; 66 | global.navigator.connection = { 67 | saveData: true 68 | }; 69 | const { useSaveData } = require('./'); 70 | const { result } = renderHook(() => useSaveData(initialSaveData)); 71 | 72 | expect(result.current.unsupported).toBe(false); 73 | expect(result.current.saveData).toEqual(navigator.connection.saveData); 74 | }); 75 | }); 76 | -------------------------------------------------------------------------------- /memory/memory.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { renderHook } from '@testing-library/react-hooks'; 18 | 19 | afterEach(function() { 20 | // Reload hook for every test 21 | jest.resetModules(); 22 | }); 23 | 24 | const getMemoryStatus = currentResult => ({ 25 | unsupported: false, 26 | deviceMemory: currentResult.deviceMemory, 27 | totalJSHeapSize: currentResult.totalJSHeapSize, 28 | usedJSHeapSize: currentResult.usedJSHeapSize, 29 | jsHeapSizeLimit: currentResult.jsHeapSizeLimit 30 | }); 31 | 32 | describe('useMemoryStatus', () => { 33 | test(`should return "true" for unsupported case`, () => { 34 | const { useMemoryStatus } = require('./'); 35 | const { result } = renderHook(() => useMemoryStatus()); 36 | 37 | expect(result.current.unsupported).toBe(true); 38 | }); 39 | 40 | test('should return initialMemoryStatus for unsupported case', () => { 41 | const mockInitialMemoryStatus = { 42 | deviceMemory: 4 43 | }; 44 | const { deviceMemory } = mockInitialMemoryStatus; 45 | 46 | const { useMemoryStatus } = require('./'); 47 | const { result } = renderHook(() => 48 | useMemoryStatus(mockInitialMemoryStatus) 49 | ); 50 | 51 | expect(result.current.unsupported).toBe(true); 52 | expect(result.current.deviceMemory).toEqual(deviceMemory); 53 | }); 54 | 55 | test('should return mockMemory status', () => { 56 | const mockMemoryStatus = { 57 | deviceMemory: 4, 58 | totalJSHeapSize: 60, 59 | usedJSHeapSize: 40, 60 | jsHeapSizeLimit: 50 61 | }; 62 | 63 | global.navigator.deviceMemory = mockMemoryStatus.deviceMemory; 64 | 65 | global.window.performance.memory = { 66 | totalJSHeapSize: mockMemoryStatus.totalJSHeapSize, 67 | usedJSHeapSize: mockMemoryStatus.usedJSHeapSize, 68 | jsHeapSizeLimit: mockMemoryStatus.jsHeapSizeLimit 69 | }; 70 | 71 | const { useMemoryStatus } = require('./'); 72 | const { result } = renderHook(() => useMemoryStatus()); 73 | 74 | expect(getMemoryStatus(result.current)).toEqual({ 75 | ...mockMemoryStatus, 76 | unsupported: false 77 | }); 78 | }); 79 | 80 | test('should return mockMemory status without performance memory data', () => { 81 | const mockMemoryStatus = { 82 | deviceMemory: 4 83 | }; 84 | 85 | global.navigator.deviceMemory = mockMemoryStatus.deviceMemory; 86 | delete global.window.performance.memory; 87 | 88 | const { useMemoryStatus } = require('./'); 89 | const { result } = renderHook(() => useMemoryStatus()); 90 | 91 | expect(result.current.deviceMemory).toEqual(mockMemoryStatus.deviceMemory); 92 | expect(result.current.unsupported).toEqual(false); 93 | }); 94 | 95 | test('should not return initialMemoryStatus for supported case', () => { 96 | const mockMemoryStatus = { 97 | deviceMemory: 4, 98 | totalJSHeapSize: 60, 99 | usedJSHeapSize: 40, 100 | jsHeapSizeLimit: 50 101 | }; 102 | const mockInitialMemoryStatus = { 103 | deviceMemory: 4 104 | }; 105 | 106 | global.navigator.deviceMemory = mockMemoryStatus.deviceMemory; 107 | 108 | global.window.performance.memory = { 109 | totalJSHeapSize: mockMemoryStatus.totalJSHeapSize, 110 | usedJSHeapSize: mockMemoryStatus.usedJSHeapSize, 111 | jsHeapSizeLimit: mockMemoryStatus.jsHeapSizeLimit 112 | }; 113 | 114 | const { useMemoryStatus } = require('./'); 115 | const { result } = renderHook(() => 116 | useMemoryStatus(mockInitialMemoryStatus) 117 | ); 118 | 119 | expect(getMemoryStatus(result.current)).toEqual({ 120 | ...mockMemoryStatus, 121 | unsupported: false 122 | }); 123 | }); 124 | }); 125 | -------------------------------------------------------------------------------- /media-capabilities/media-capabilities.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import 'babel-polyfill'; 18 | import { renderHook } from '@testing-library/react-hooks'; 19 | 20 | const mediaDecodingConfig = { 21 | type: 'file', 22 | audio: { 23 | contentType: 'audio/mp3', 24 | channels: 2, 25 | bitrate: 132700, 26 | samplerate: 5200 27 | } 28 | }; 29 | 30 | const mediaCapabilitiesMapper = { 31 | 'audio/mp3': { 32 | powerEfficient: true, 33 | smooth: true, 34 | supported: true 35 | } 36 | }; 37 | 38 | describe('useMediaCapabilitiesDecodingInfo', () => { 39 | test('should return supported flag on unsupported platforms', () => { 40 | const { useMediaCapabilitiesDecodingInfo } = require('./'); 41 | const { result } = renderHook(() => useMediaCapabilitiesDecodingInfo(mediaDecodingConfig)); 42 | 43 | expect(result.current.supported).toEqual(false); 44 | }); 45 | 46 | test('should return supported flag on unsupported platforms and no config given', () => { 47 | const { useMediaCapabilitiesDecodingInfo } = require('./'); 48 | const { result } = renderHook(() => useMediaCapabilitiesDecodingInfo()); 49 | 50 | expect(result.current.supported).toEqual(false); 51 | }); 52 | 53 | test('should return initialMediaCapabilitiesInfo for unsupported', () => { 54 | const initialMediaCapabilitiesInfo = { 55 | supported: true, 56 | smooth: false, 57 | powerEfficient: true 58 | }; 59 | 60 | const { useMediaCapabilitiesDecodingInfo } = require('./'); 61 | const { result } = renderHook(() => useMediaCapabilitiesDecodingInfo(mediaDecodingConfig, initialMediaCapabilitiesInfo)); 62 | 63 | expect(result.current.mediaCapabilitiesInfo.supported).toBe(true); 64 | expect(result.current.mediaCapabilitiesInfo.smooth).toEqual(false); 65 | expect(result.current.mediaCapabilitiesInfo.powerEfficient).toEqual(true); 66 | }); 67 | 68 | test('should return supported flag when no config given', async () => { 69 | const originalError = console.error; 70 | console.error = jest.fn(); 71 | 72 | const mockDecodingInfo = jest.fn().mockImplementation(() => Promise.resolve({ 73 | supported: true 74 | })); 75 | 76 | global.navigator.mediaCapabilities = { 77 | decodingInfo: mockDecodingInfo 78 | }; 79 | 80 | const { useMediaCapabilitiesDecodingInfo } = require('./'); 81 | 82 | try { 83 | const { result, waitForNextUpdate } = renderHook(() => useMediaCapabilitiesDecodingInfo()); 84 | await waitForNextUpdate(); 85 | 86 | expect(result.current.supported).toEqual(true); 87 | } finally { 88 | console.error = originalError; 89 | } 90 | }); 91 | 92 | test('should return mediaCapabilitiesInfo for given media configuration', async () => { 93 | const originalError = console.error; 94 | console.error = jest.fn(); 95 | 96 | const mockDecodingInfo = jest.fn().mockImplementation(() => Promise.resolve({ 97 | ...mediaCapabilitiesMapper[mediaDecodingConfig.audio.contentType] 98 | })); 99 | 100 | global.navigator.mediaCapabilities = { 101 | decodingInfo: mockDecodingInfo 102 | }; 103 | 104 | const { useMediaCapabilitiesDecodingInfo } = require('./'); 105 | 106 | try { 107 | const { result, waitForNextUpdate } = renderHook(() => useMediaCapabilitiesDecodingInfo(mediaDecodingConfig)); 108 | await waitForNextUpdate(); 109 | 110 | expect(result.current.mediaCapabilitiesInfo.powerEfficient).toEqual(true); 111 | expect(result.current.mediaCapabilitiesInfo.smooth).toEqual(true); 112 | expect(result.current.mediaCapabilitiesInfo.supported).toEqual(true); 113 | } finally { 114 | console.error = originalError; 115 | } 116 | }); 117 | }); 118 | -------------------------------------------------------------------------------- /network/network.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { renderHook, act } from '@testing-library/react-hooks'; 18 | 19 | import { useNetworkStatus } from './'; 20 | 21 | describe('useNetworkStatus', () => { 22 | const map = {}; 23 | 24 | const ectStatusListeners = { 25 | addEventListener: jest.fn().mockImplementation((event, callback) => { 26 | map[event] = callback; 27 | }), 28 | removeEventListener: jest.fn() 29 | }; 30 | 31 | afterEach(() => { 32 | Object.values(ectStatusListeners).forEach(listener => listener.mockClear()); 33 | }); 34 | 35 | /** 36 | * Tests that addEventListener or removeEventListener was called during the 37 | * lifecycle of the useEffect hook within useNetworkStatus 38 | */ 39 | const testEctStatusEventListenerMethod = method => { 40 | expect(method).toBeCalledTimes(1); 41 | expect(method.mock.calls[0][0]).toEqual('change'); 42 | expect(method.mock.calls[0][1].constructor).toEqual(Function); 43 | }; 44 | 45 | test(`should return "true" for unsupported case`, () => { 46 | const { result } = renderHook(() => useNetworkStatus()); 47 | 48 | expect(result.current.unsupported).toBe(true); 49 | }); 50 | 51 | test('should return initialEffectiveConnectionType for unsupported case', () => { 52 | const initialEffectiveConnectionType = '4g'; 53 | 54 | const { result } = renderHook(() => 55 | useNetworkStatus(initialEffectiveConnectionType) 56 | ); 57 | 58 | expect(result.current.unsupported).toBe(true); 59 | expect(result.current.effectiveConnectionType).toBe( 60 | initialEffectiveConnectionType 61 | ); 62 | }); 63 | 64 | test('should return 4g of effectiveConnectionType', () => { 65 | global.navigator.connection = { 66 | ...ectStatusListeners, 67 | effectiveType: '4g' 68 | }; 69 | 70 | const { result } = renderHook(() => useNetworkStatus()); 71 | 72 | testEctStatusEventListenerMethod(ectStatusListeners.addEventListener); 73 | expect(result.current.unsupported).toBe(false); 74 | expect(result.current.effectiveConnectionType).toEqual('4g'); 75 | }); 76 | 77 | test('should not return initialEffectiveConnectionType for supported case', () => { 78 | const initialEffectiveConnectionType = '2g'; 79 | global.navigator.connection = { 80 | ...ectStatusListeners, 81 | effectiveType: '4g' 82 | }; 83 | 84 | const { result } = renderHook(() => 85 | useNetworkStatus(initialEffectiveConnectionType) 86 | ); 87 | 88 | testEctStatusEventListenerMethod(ectStatusListeners.addEventListener); 89 | expect(result.current.unsupported).toBe(false); 90 | expect(result.current.effectiveConnectionType).toEqual('4g'); 91 | }); 92 | 93 | test('should update the effectiveConnectionType state', () => { 94 | const { result } = renderHook(() => useNetworkStatus()); 95 | 96 | act(() => 97 | result.current.setNetworkStatus({ effectiveConnectionType: '2g' }) 98 | ); 99 | 100 | expect(result.current.effectiveConnectionType).toEqual('2g'); 101 | }); 102 | 103 | test('should update the effectiveConnectionType state when navigator.connection change event', () => { 104 | global.navigator.connection = { 105 | ...ectStatusListeners, 106 | effectiveType: '2g' 107 | }; 108 | 109 | const { result } = renderHook(() => useNetworkStatus()); 110 | global.navigator.connection.effectiveType = '4g'; 111 | act(() => map.change()); 112 | 113 | expect(result.current.effectiveConnectionType).toEqual('4g'); 114 | }); 115 | 116 | test('should remove the listener for the navigator.connection change event on unmount', () => { 117 | global.navigator.connection = { 118 | ...ectStatusListeners, 119 | effectiveType: '2g' 120 | }; 121 | 122 | const { unmount } = renderHook(() => useNetworkStatus()); 123 | 124 | testEctStatusEventListenerMethod(ectStatusListeners.addEventListener); 125 | unmount(); 126 | testEctStatusEventListenerMethod(ectStatusListeners.removeEventListener); 127 | }); 128 | }); 129 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Adaptive Loading Hooks & Utilities · ![](https://img.shields.io/github/license/GoogleChromeLabs/react-adaptive-hooks.svg) [![Build Status](https://travis-ci.org/GoogleChromeLabs/react-adaptive-hooks.svg?branch=master)](https://travis-ci.org/GoogleChromeLabs/react-adaptive-hooks) ![npm bundle size](https://img.shields.io/bundlephobia/minzip/react-adaptive-hooks) 2 | 3 | > Deliver experiences best suited to a user's device and network constraints (experimental) 4 | 5 | This is a suite of [React Hooks](https://reactjs.org/docs/hooks-overview.html) and utilities for adaptive loading based on a user's: 6 | 7 | * [Network via effective connection type](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/effectiveType) 8 | * [Data Saver preferences](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData) 9 | * [Device memory](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/deviceMemory) 10 | * [Logical CPU cores](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency) 11 | * [Media Capabilities API](https://developer.mozilla.org/en-US/docs/Web/API/Media_Capabilities_API) 12 | 13 | It can be used to add patterns for adaptive resource loading, data-fetching, code-splitting and capability toggling. 14 | 15 | ## Objective 16 | 17 | 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. 18 | 19 | ## Installation 20 | 21 | `npm i react-adaptive-hooks --save` or `yarn add react-adaptive-hooks` 22 | 23 | ## Usage 24 | 25 | You can import the hooks you wish to use as follows: 26 | 27 | ```js 28 | import { useNetworkStatus } from 'react-adaptive-hooks/network'; 29 | import { useSaveData } from 'react-adaptive-hooks/save-data'; 30 | import { useHardwareConcurrency } from 'react-adaptive-hooks/hardware-concurrency'; 31 | import { useMemoryStatus } from 'react-adaptive-hooks/memory'; 32 | import { useMediaCapabilitiesDecodingInfo } from 'react-adaptive-hooks/media-capabilities'; 33 | ``` 34 | 35 | and then use them in your components. Examples for each hook and utility can be found below: 36 | 37 | ### Network 38 | 39 | `useNetworkStatus` React hook for adapting based on network status (effective connection type) 40 | 41 | ```js 42 | import React from 'react'; 43 | 44 | import { useNetworkStatus } from 'react-adaptive-hooks/network'; 45 | 46 | const MyComponent = () => { 47 | const { effectiveConnectionType } = useNetworkStatus(); 48 | 49 | let media; 50 | switch(effectiveConnectionType) { 51 | case 'slow-2g': 52 | media = low resolution; 53 | break; 54 | case '2g': 55 | media = medium resolution; 56 | break; 57 | case '3g': 58 | media = high resolution; 59 | break; 60 | case '4g': 61 | media = ; 62 | break; 63 | default: 64 | media = ; 65 | break; 66 | } 67 | 68 | return
{media}
; 69 | }; 70 | ``` 71 | 72 | `effectiveConnectionType` values can be `slow-2g`, `2g`, `3g`, or `4g`. 73 | 74 | 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](https://wicg.github.io/netinfo/). Passing an initial value can also prove useful for server-side rendering, where the developer can pass an [ECT Client Hint](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/client-hints#ect) to detect the effective network connection type. 75 | 76 | ```js 77 | // Inside of a functional React component 78 | const initialEffectiveConnectionType = '4g'; 79 | const { effectiveConnectionType } = useNetworkStatus(initialEffectiveConnectionType); 80 | ``` 81 | 82 | ### Save Data 83 | 84 | `useSaveData` utility for adapting based on the user's browser Data Saver preferences. 85 | 86 | ```js 87 | import React from 'react'; 88 | 89 | import { useSaveData } from 'react-adaptive-hooks/save-data'; 90 | 91 | const MyComponent = () => { 92 | const { saveData } = useSaveData(); 93 | return ( 94 |
95 | { saveData ? : } 96 |
97 | ); 98 | }; 99 | ``` 100 | 101 | `saveData` values can be `true` or `false`. 102 | 103 | 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](https://wicg.github.io/netinfo/). Passing an initial value can also prove useful for server-side rendering, where the developer can pass a server [Save-Data Client Hint](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/client-hints#save-data) that has been converted to a boolean to detect the user's data saving preference. 104 | 105 | ```js 106 | // Inside of a functional React component 107 | const initialSaveData = true; 108 | const { saveData } = useSaveData(initialSaveData); 109 | ``` 110 | 111 | ### CPU Cores / Hardware Concurrency 112 | 113 | `useHardwareConcurrency` utility for adapting to the number of logical CPU processor cores on the user's device. 114 | 115 | ```js 116 | import React from 'react'; 117 | 118 | import { useHardwareConcurrency } from 'react-adaptive-hooks/hardware-concurrency'; 119 | 120 | const MyComponent = () => { 121 | const { numberOfLogicalProcessors } = useHardwareConcurrency(); 122 | return ( 123 |
124 | { numberOfLogicalProcessors <= 4 ? : } 125 |
126 | ); 127 | }; 128 | ``` 129 | 130 | `numberOfLogicalProcessors` values can be the number of logical processors available to run threads on the user's device. 131 | 132 | ### Memory 133 | 134 | `useMemoryStatus` utility for adapting based on the user's device memory (RAM) 135 | 136 | ```js 137 | import React from 'react'; 138 | 139 | import { useMemoryStatus } from 'react-adaptive-hooks/memory'; 140 | 141 | const MyComponent = () => { 142 | const { deviceMemory } = useMemoryStatus(); 143 | return ( 144 |
145 | { deviceMemory < 4 ? : } 146 |
147 | ); 148 | }; 149 | ``` 150 | 151 | `deviceMemory` values can be the approximate amount of device memory in gigabytes. 152 | 153 | 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](https://github.com/w3c/device-memory). Passing an initial value can also prove useful for server-side rendering, where the developer can pass a server [Device-Memory Client Hint](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/client-hints#save-data) to detect the memory capacity of the user's device. 154 | 155 | ```js 156 | // Inside of a functional React component 157 | const initialMemoryStatus = { deviceMemory: 4 }; 158 | const { deviceMemory } = useMemoryStatus(initialMemoryStatus); 159 | ``` 160 | 161 | ### Media Capabilities 162 | 163 | `useMediaCapabilitiesDecodingInfo` utility for adapting based on the user's device media capabilities. 164 | 165 | **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. 166 | 167 | ```js 168 | import React from 'react'; 169 | 170 | import { useMediaCapabilitiesDecodingInfo } from 'react-adaptive-hooks/media-capabilities'; 171 | 172 | const webmMediaDecodingConfig = { 173 | type: 'file', // 'record', 'transmission', or 'media-source' 174 | video: { 175 | contentType: 'video/webm;codecs=vp8', // valid content type 176 | width: 800, // width of the video 177 | height: 600, // height of the video 178 | bitrate: 10000, // number of bits used to encode 1s of video 179 | framerate: 30 // number of frames making up that 1s. 180 | } 181 | }; 182 | 183 | const initialMediaCapabilitiesInfo = { powerEfficient: true }; 184 | 185 | const MyComponent = ({ videoSources }) => { 186 | const { mediaCapabilitiesInfo } = useMediaCapabilitiesDecodingInfo(webmMediaDecodingConfig, initialMediaCapabilitiesInfo); 187 | 188 | return ( 189 |
190 | 191 |
192 | ); 193 | }; 194 | ``` 195 | 196 | `mediaCapabilitiesInfo` value contains the three Boolean properties supported, smooth, and powerEfficient, which describe whether decoding the media described would be supported, smooth, and powerEfficient. 197 | 198 | This utility accepts a [MediaDecodingConfiguration](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/Media_Capabilities_API) or no media configuration was given. 199 | 200 | ### Adaptive Code-loading & Code-splitting 201 | 202 | #### Code-loading 203 | 204 | 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: 205 | 206 | ```js 207 | import React, { Suspense, lazy } from 'react'; 208 | 209 | import { useNetworkStatus } from 'react-adaptive-hooks/network'; 210 | 211 | const Full = lazy(() => import(/* webpackChunkName: "full" */ './Full.js')); 212 | const Light = lazy(() => import(/* webpackChunkName: "light" */ './Light.js')); 213 | 214 | const MyComponent = () => { 215 | const { effectiveConnectionType } = useNetworkStatus(); 216 | return ( 217 |
218 | Loading...
}> 219 | { effectiveConnectionType === '4g' ? : } 220 | 221 | 222 | ); 223 | }; 224 | 225 | export default MyComponent; 226 | ``` 227 | 228 | Light.js: 229 | ```js 230 | import React from 'react'; 231 | 232 | const Light = ({ imageUrl, ...rest }) => ( 233 | 234 | ); 235 | 236 | export default Light; 237 | ``` 238 | 239 | Full.js: 240 | ```js 241 | import React from 'react'; 242 | import Magnifier from 'react-magnifier'; 243 | 244 | const Full = ({ imageUrl, ...rest }) => ( 245 | 246 | ); 247 | 248 | export default Full; 249 | ``` 250 | 251 | #### Code-splitting 252 | 253 | 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`). 254 | 255 | ```js 256 | import React, { Suspense } from 'react'; 257 | 258 | const Component = React.lazy(() => { 259 | const effectiveType = navigator.connection ? navigator.connection.effectiveType : null 260 | 261 | let module; 262 | switch (effectiveType) { 263 | case '3g': 264 | module = import(/* webpackChunkName: "light" */ './Light.js'); 265 | break; 266 | case '4g': 267 | module = import(/* webpackChunkName: "full" */ './Full.js'); 268 | break; 269 | default: 270 | module = import(/* webpackChunkName: "full" */ './Full.js'); 271 | break; 272 | } 273 | 274 | return module; 275 | }); 276 | 277 | const App = () => { 278 | return ( 279 |
280 | Loading...
}> 281 | 282 | 283 | 284 | ); 285 | }; 286 | 287 | export default App; 288 | ``` 289 | 290 | ## Server-side rendering support 291 | 292 | 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 293 | 294 | * Transpile the package by installing [next-transpile-modules](https://github.com/martpie/next-transpile-modules). ([example project](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/next-show-adaptive-loading)). This is because Next.js currently does not pass `node_modules` into webpack server-side. 295 | 296 | * Use a UMD build as in the following code-snippet: ([example project](https://glitch.com/edit/#!/anton-karlovskiy-next-show-adaptive-loading?path=utils/hooks.js:19:91)) 297 | ``` 298 | import { 299 | useNetworkStatus, 300 | useSaveData, 301 | useHardwareConcurrency, 302 | useMemoryStatus, 303 | useMediaCapabilitiesDecodingInfo 304 | } from 'react-adaptive-hooks/dist/index.umd.js'; 305 | ``` 306 | 307 | ## Browser Support 308 | 309 | * [Network Information API - effectiveType](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/effectiveType) is available in [Chrome 61+, Opera 48+, Edge 76+, Chrome for Android 76+, Firefox for Android 68+](https://caniuse.com/#search=effectiveType) 310 | 311 | * [Save Data API](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData) is available in [Chrome 65+, Opera 62+, Chrome for Android 76+, Opera for Android 46+](https://caniuse.com/#search=saveData) 312 | 313 | * [Hardware Concurrency API](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency) is available in [Chrome 37+, Safari 10.1+, Firefox 48+, Opera 24+, Edge 15+, Chrome for Android 76+, Safari on iOS 10.3+, Firefox for Android 68+, Opera for Android 46+](https://caniuse.com/#search=navigator.hardwareConcurrency) 314 | 315 | * [Performance memory API](https://developer.mozilla.org/en-US/docs/Web/API/Performance) is a non-standard and only available in [Chrome 7+, Opera, Chrome for Android 18+, Opera for Android](https://developer.mozilla.org/en-US/docs/Web/API/Performance/memory) 316 | 317 | * [Device Memory API](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/deviceMemory) is available in [Chrome 63+, Opera 50+, Chrome for Android 76+, Opera for Android 46+](https://caniuse.com/#search=deviceMemory) 318 | 319 | * [Media Capabilities API](https://developer.mozilla.org/en-US/docs/Web/API/Media_Capabilities_API) is available in [Chrome 63+, Firefox 63+, Opera 55+, Chrome for Android 78+, Firefox for Android 68+](https://caniuse.com/#search=media%20capabilities) 320 | 321 | ## Demos 322 | 323 | ### Network 324 | 325 | * [Network-aware loading](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/cra-network-aware-loading) with create-react-app ([Live](https://adaptive-loading.web.app/cra-network-aware-loading/)) 326 | * [Network-aware code-splitting](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/cra-network-aware-code-splitting) with create-react-app ([Live](https://adaptive-loading.web.app/cra-network-aware-code-splitting/)) 327 | * [Network-aware data-fetching](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/cra-network-aware-data-fetching) with create-react-app ([Live](https://adaptive-loading.web.app/cra-network-aware-data-fetching/)) 328 | 329 | * [React Movie - network-aware loading](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/react-movie-network-aware-loading) ([Live](https://adaptive-loading.web.app/react-movie-network-aware-loading/)) 330 | * [React Shrine - network-aware code-splitting](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/react-shrine-network-aware-code-splitting) ([Live](https://adaptive-loading.web.app/react-shrine-network-aware-code-splitting/)) 331 | * [React eBay - network-aware code-splitting](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/react-ebay-network-aware-code-splitting) ([Live](https://adaptive-loading.web.app/react-ebay-network-aware-code-splitting/)) 332 | * [React Lottie - network-aware loading](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/react-lottie-network-aware-loading) ([Live](https://adaptive-loading.web.app/react-lottie-network-aware-loading/)) 333 | 334 | ### Save Data 335 | 336 | * [React Twitter - save-data loading based on Client Hint](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/react-twitter-save-data-loading(client-hint)) ([Live](https://adaptive-loading.web.app/react-twitter-save-data-loading(client-hint)/)) 337 | * [React Twitter - save-data loading based on Hook](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/react-twitter-save-data-loading(hook)) ([Live](https://adaptive-loading.web.app/react-twitter-save-data-loading(hook)/)) 338 | 339 | ### CPU Cores / Hardware Concurrency 340 | 341 | * [Hardware concurrency considerate code-splitting](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/cra-hardware-concurrency-considerate-code-splitting) with create-react-app ([Live](https://adaptive-loading.web.app/cra-hardware-concurrency-considerate-code-splitting/)) 342 | * [Hardware concurrency considerate loading](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/cra-hardware-concurrency-considerate-loading) with create-react-app ([Live](https://adaptive-loading.web.app/cra-hardware-concurrency-considerate-loading/)) 343 | 344 | ### Memory 345 | 346 | * [Memory considerate loading](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/cra-memory-considerate-loading) with create-react-app ([Live](https://adaptive-loading.web.app/cra-memory-considerate-loading/)) 347 | * [Memory considerate loading (SketchFab version)](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/cra-memory-considerate-loading-sketchfab) with create-react-app ([Live](https://adaptive-loading.web.app/cra-memory-considerate-loading-sketchfab/)) 348 | * [Memory-considerate animation-toggling](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/cna-memory-considerate-animation) with create-next-app ([Live](https://adaptive-loading.web.app/cna-memory-considerate-animation/)) 349 | 350 | * [React Dixie Mesh - memory considerate loading](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/react-dixie-memory-considerate-loading) ([Live](https://adaptive-loading.web.app/react-dixie-memory-considerate-loading/)) 351 | 352 | ### Hybrid 353 | 354 | * [React Youtube - adaptive loading with mix of network, memory and hardware concurrency](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/react-youtube-adaptive-loading) ([Live](https://adaptive-loading.web.app/react-youtube-adaptive-loading/)) 355 | * [Next Show - adaptive loading with mix of network, memory and Client Hints](https://github.com/GoogleChromeLabs/adaptive-loading/tree/master/next-show-adaptive-loading) ([demo](https://adaptive-loading.web.app/next-show-adaptive-loading/)) 356 | 357 | ## References 358 | 359 | * [Adaptive serving based on network quality](https://web.dev/adaptive-serving-based-on-network-quality/) 360 | * [Adaptive Serving using JavaScript and the Network Information API](https://addyosmani.com/blog/adaptive-serving/) 361 | * [Serving Adaptive Components Using the Network Information API](https://dev.to/vorillaz/serving-adaptive-components-using-the-network-information-api-lbo) 362 | 363 | ## License 364 | 365 | Licensed under the Apache-2.0 license. 366 | 367 | ## Team 368 | 369 | This project is brought to you by [Addy Osmani](https://github.com/addyosmani) and [Anton Karlovskiy](https://github.com/anton-karlovskiy). 370 | --------------------------------------------------------------------------------