Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3554

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T03:48:08+00:00 2024-11-26T03:48:08+00:00

Optimizing UX: The Art of Adaptive Loading in Web Performance

  • 61k

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

npm install react-adaptive-hooks 
Enter fullscreen mode Exit fullscreen mode

For yarn users, execute the following command in the terminal

yarn add react-adaptive-hooks 
Enter fullscreen mode Exit fullscreen mode

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.

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>; }; 
Enter fullscreen mode Exit fullscreen mode

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.

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>   ); }; 
Enter fullscreen mode Exit fullscreen mode

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.

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>   ); }; 
Enter fullscreen mode Exit fullscreen mode

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.

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>   ); }; 
Enter fullscreen mode Exit fullscreen mode

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.

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>   ); }; 
Enter fullscreen mode Exit fullscreen mode

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:

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; 
Enter fullscreen mode Exit fullscreen mode

Light.js:

import React from 'react';  const Light = ({ imageUrl, ...rest }) => (   <img src={imageUrl} {...rest} /> );  export default Light; 
Enter fullscreen mode Exit fullscreen mode

Full.js:

import React from 'react'; import Magnifier from 'react-magnifier';  const Full = ({ imageUrl, ...rest }) => (   <Magnifier src={imageUrl} {...rest} /> );  export default Full; 
Enter fullscreen mode Exit fullscreen mode

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

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; 
Enter fullscreen mode Exit fullscreen mode

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 and Twitter.

frontendreactwebdevwebperf
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.