热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ReactConcurrentMode-TheFutureofWebApps

WhenitcomestogreatUX,performanceisoneofthekeyfactors.Whileworkingonlargescaleapplicationsweoftenencountersituationswherewehavetocompromiseuserexperiencetokeepourappsfast.Butwhatifwecouldfindawaytobuil

In a recent post , we discussed building great user experiences using React Suspense. Continuing on that post, we will have a look at how React’s new experimental Concurrent mode helps us develop responsive and fast apps. 

When it comes to great UX, performance is one of the key factors. While working on large scale applications we often encounter situations where we have to compromise user experience to keep our apps fast. But what if we could find a way to build apps that are highly performant by default with smooth UX and developer-friendly APIs? React Concurrent Mode is the answer to all of these wishes.

Concurrent React is something that has been under development at Facebook for the past 2 years now. React Fiber, a complete rewrite of React, was done with concurrent mode as central motivation. Though all of the other benefits of React Fiber are worth it themselves but enabling Interruptible Rendering and concurrency is the best amongst them.

React Concurrent Mode - A Theory

What is concurrent React?! As React Docs mention:

Concurrent Mode is a set of new features that help React apps stay responsive and gracefully adjust to the user’s device capabilities and network speed.

Diving deep, Concurrent React can work on multiple tasks at a time and can switch between them depending upon the priority. 

The way UI libraries work today is the blocking render approach: when the library has started rendering it cannot go back, no matter how important the next update is. For example, once the browser has started rendering a list of search results, any change in the search input field has to wait until this rendering is finished. 

This is not the case anymore with concurrent mode. React starts rendering updates in memory and high priority tasks such as a change in an input field can interrupt that rendering process. So when there is a change, React will let the browser paint the change and the rendering process will continue once this high priority task is completed. 

Afterward, upon completion of list rendering, React will commit it to DOM and also be displayed on the screen. In short, With Concurrent React, you can render large amounts of work without blocking user inputs and other high priority tasks on the main thread.

Add ButterCMS to your React app in minutes

Concurrent React can partially render a tree without committing the result to the DOM. For example, React starts rendering an update and it encounters a component that hasn’t finished loading. React will wait for loading to be finished without necessarily rendering some fallback component.

One of the best use cases to demonstrate this will be navigation between different pages. Once a user taps on a link and code to display the component,  an appropriate loading state is not available. Here React can wait for a little and keep showing the current screen fully interactive to avoid bad loading state. Once sufficient data or code is available this transition can be completed. Though it can be done via different techniques Concurrent mode makes it more intuitive for developers.

All of this is done by just a few lines of code as React uses heuristics to decide how urgent updates are.

Enabling React Concurrent Mode

As we discussed in our previous post , the developer experience has been at the core of React’s growth. The same goes for Concurrent React, as it is super easy to adopt. Either you’re relying on class components or cruising with hooks, Concurrent React will support both.

Though Concurrent React is used in production at Facebook, for open source users its available in an experimental version of React. To install the experimental version you can use the following command

npm install react@experimental react-dom@experimental

Unlike other features that don’t require any changes in the existing code base, Concurrent mode requires a little change on the root of the React component tree. Here is that small change

import ReactDOM from 'react-dom';

// Current React - Or Blocking Rendering React:
//
// ReactDOM.render(, document.getElementById('root'));
//
// Concurrent Mode - Or Interruptible Rendering React:

ReactDOM.createRoot(
  document.getElementById('root')
).render();

One important notice here, the lifecycle methods that were marked as UNSAFE_ in previous React releases are truly unsafe with Concurrent Mode. It is highly recommended that you move to new lifecycle methods for a secure transition to Concurrent Mode.

Understanding APIs

In order to fully utilize Concurrent Mode and develop highly responsive interfaces, React gives developers an intuitive API to handle the transition between states and loading states. 

useTransition

As discussed above unlike blocking rendering where all updates are treated with the same priority, Concurrent Mode allows developers to de-prioritize slower updates to keep interfaces interactive. 

The useTransition hook allows developers to schedule work after higher priority work.

Continuing with an example of showing search results under input, updates in the input are of highest priority to keep UI interactable. However, fetching data and rendering lists is of low priority. Wrapping our update in startTransition communicates to React that these updates are of lower priority and can be scheduled after high priority tasks. 

A number of research about handling loading states suggests that gestures like hover and input change should be handled at the highest priority to avoid laggy outlook of the interface. However, a little bit of wait on click and during page transitions is bearable for users. Supporting this research useTransition hook allows developers to wait for a time period before displaying any loading state.

Here is full API of useTransition hook:

const [startTransition, isPending] = useTransition({
  timeoutMs: 2000,
});

startTransition - Method to wrap low priority updates  

isPending - Boolean indicating if there is any pending low priority update, likely used for showing loading state.

timeoutMs - Milliseconds after the update is marked as pending.

useDeferredValue

React Concurrent Mode allows developers to produce the magic of useTransition themselves . With useTransition we get isPending available right away, whereas useDefferedValue gives us the previous value of state that is in transition. API looks like the following:

const deferredValue = useDeferredValue(value, { timeoutMs: 2000 });

deferredValue will have a previous version of the value for at most timeout milliseconds.

Add ButterCMS to your React app in minutes

This is commonly used to keep the interface responsive when you have something that renders immediately based on user input and something that needs to wait for a data fetch.

SuspenseList

SuspenseList is a component that wraps a bunch of child Suspense components and gives you handles for how to show all of the various loading states.

In apps that render a number of suspense components together, SuspenseList provides the ability to handle how these components are revealed to the user. Let's take an example to render a list of Blog posts on our page. List Component of our page will look like the following.


  }>
    
  
  }>
    
  
  }>
    
  
  ...

SuspenseList takes two props:

  • revealOrder: [forwards | backwards | together] It defines the order in which the children Suspense components should be revealed.
    • together : Quite similar to the  Promise.all API, it renders complete list once all items are available
    • forwards/backwards : This will reveal in sequence one after another, top-down or bottom, even if the component after next is ready it will keep it suspended until the next component is revealed.
  • tail: [collapsed | hidden] It determines how suspended items in the list are shown. By default React will display fallback for all items in the list. 
    • collapsed : It will show only the fallback of the next item in the list
    • hidden : It will hide all fallbacks in the list

Conclusion

As we see today, React Concurrent Mode will allow front-end engineers to develop fast, reliable and scalable interfaces easily, paving the way for higher standards in user experience.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 我们


推荐阅读
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 阿里Treebased Deep Match(TDM) 学习笔记及技术发展回顾
    本文介绍了阿里Treebased Deep Match(TDM)的学习笔记,同时回顾了工业界技术发展的几代演进。从基于统计的启发式规则方法到基于内积模型的向量检索方法,再到引入复杂深度学习模型的下一代匹配技术。文章详细解释了基于统计的启发式规则方法和基于内积模型的向量检索方法的原理和应用,并介绍了TDM的背景和优势。最后,文章提到了向量距离和基于向量聚类的索引结构对于加速匹配效率的作用。本文对于理解TDM的学习过程和了解匹配技术的发展具有重要意义。 ... [详细]
  • 本文介绍了在rhel5.5操作系统下搭建网关+LAMP+postfix+dhcp的步骤和配置方法。通过配置dhcp自动分配ip、实现外网访问公司网站、内网收发邮件、内网上网以及SNAT转换等功能。详细介绍了安装dhcp和配置相关文件的步骤,并提供了相关的命令和配置示例。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文介绍了Hyperledger Fabric外部链码构建与运行的相关知识,包括在Hyperledger Fabric 2.0版本之前链码构建和运行的困难性,外部构建模式的实现原理以及外部构建和运行API的使用方法。通过本文的介绍,读者可以了解到如何利用外部构建和运行的方式来实现链码的构建和运行,并且不再受限于特定的语言和部署环境。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • 本文介绍了Perl的测试框架Test::Base,它是一个数据驱动的测试框架,可以自动进行单元测试,省去手工编写测试程序的麻烦。与Test::More完全兼容,使用方法简单。以plural函数为例,展示了Test::Base的使用方法。 ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • Ubuntu 9.04中安装谷歌Chromium浏览器及使用体验[图文]
    nsitionalENhttp:www.w3.orgTRxhtml1DTDxhtml1-transitional.dtd ... [详细]
  • 本文介绍了如何使用Express App提供静态文件,同时提到了一些不需要使用的文件,如package.json和/.ssh/known_hosts,并解释了为什么app.get('*')无法捕获所有请求以及为什么app.use(express.static(__dirname))可能会提供不需要的文件。 ... [详细]
  • 本文介绍了在CentOS上安装Python2.7.2的详细步骤,包括下载、解压、编译和安装等操作。同时提供了一些注意事项,以及测试安装是否成功的方法。 ... [详细]
  • 树莓派语音控制的配置方法和步骤
    本文介绍了在树莓派上实现语音控制的配置方法和步骤。首先感谢博主Eoman的帮助,文章参考了他的内容。树莓派的配置需要通过sudo raspi-config进行,然后使用Eoman的控制方法,即安装wiringPi库并编写控制引脚的脚本。具体的安装步骤和脚本编写方法在文章中详细介绍。 ... [详细]
author-avatar
赤木律孑
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有