Intro to React Suspense and concurrent mode

栏目: IT技术 · 发布时间: 4年前

内容简介:There has been plenty of interest in React Suspense with many articles and experimental code snippets to test it out. I thought I would read more about it and give my understanding of why you might want to use it. Below is my summary after reading through

There has been plenty of interest in React Suspense with many articles and experimental code snippets to test it out. I thought I would read more about it and give my understanding of why you might want to use it. Below is my summary after reading through the React docs about concurrent mode and Suspense .

Intro to React Suspense and concurrent mode Photo by Faye Cornish on Unsplash

React concurrent mode

It’s about making the UI more responsive and fluid for better user experience by preventing render-blocking updates. When React begins to render, there is no way to stop it and begin on a higher priority change. However, with concurrent mode, it’s possible to interrupt the render to show the user the latest change and prevent the UI from staggering as it updates.

Two key points for concurrent mode:

Interruptible rendering

Works well for when user interactions are quick, for example typing a message and tagging a person in it is typically supported with a suggestion/auto-complete list. With a typical implementation, these lists can be quite jumpy for each character added, but with concurrent mode, it can interrupt a render with the latest changes.

Intentional loading sequences

When transitioning to another page there might not be enough data to render a complete loading page, so it shows a blank page for a brief moment. It’s possible to wait for a little on the current page and begin rendering the loader in memory first. Then it can update the UI with a controlled transition to prevent a jarring experience.

React Suspense

Since React 16.6 a new component called Suspense was introduced which can be used to manage the loading states while resolving async requests. This is an experimental component and is likely to change - so keep that in mind. The interesting thing about this component is it’s unaware of any data fetching API and essentially decouples fetching data from the view layer. As mentioned in the React docs, this is not a ready to use data client that would replace fetch API, Apollo or Relay. What it does enable is a more natural React interface to integrate ways to fetch data. Data libraries would need to implement the Suspense API for consumers to use this component.

Suspense in practice

Typically in a React application, you would fetch-on-render , which is fetching data in componentDidMount or useEffect life cycles. Once data is resolved successfully update the component state to render the view.

Example of fetch on render:

function ListPosts() {
  const [tweets, setTweets] = useState({
    loading: true,
    data: []
  });
  useEffect(async () => {
    const posts = await dataSource.twitter.getTweets();
    setTweets({
      loading: false,
      data: posts
    });
  }, []);

  if(tweets.loading){
    return <h1>Loading tweets...</h1>;
  }

  return (
    <ul>
      {tweets.data.map(tweet => (
        <li key={tweet.id}>{tweet.text}</li>
      ))}
    </ul>
  );
}

Typical flow:

  1. Render loading view
  2. Wait for the component to mount
  3. Start fetching tweets
  4. Wait to resolve tweets
  5. Update state to render a list of tweets

The Suspense approach is render-as-you-fetch meaning you begin fetching data before the component starts to render. There is no need to use life cycle events and manage state when components are wrapped in the Suspense component.

function TwitterTimeline() {
  // notice no async/await, just try to get tweets
  const tweets = suspenseDataSource.twitter.getTweets();
  return (
    <ul>
      {tweets.map(tweet => (
        <li key={tweet.id}>{tweet.text}</li>
      ))}
    </ul>
  );
}

function ListPosts(){
  <Suspense fallback={<h1>Loading tweets...</h1>}>
    <TwitterTimeline />
  </Suspense>
}

Suspense flow:

  1. Start fetching tweets
  2. Start rendering tweets
  3. If not ready suspend rendering
  4. Fallback to loading view
  5. Resolve tweets to render

The Suspense approach is noticeably different from the typical way. In code, you might feel it’s easier to reason about. The removal of logic loading state and life cycle events reduce complexity. From the user perspective, they get a more responsive UI because we are starting to resolve data first while rendering.

This does look like a win-win for both end-users and developers. See the Code Sandbox Suspense example by Dan Abramov . I would recommend reading the React docs on Suspense to get more details if you’re interested.

I hope this helps you understand React Suspense and concurrent mode more. Comment onor below.


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

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

硅谷之谜

硅谷之谜

吴军 / 人民邮电出版社 / 2015-12-1 / 59.00

这是一本颠覆人们对信息时代的认识、对创新和创业的理解的好书。作者吴军通过介绍硅谷成功的秘诀,揭示了信息时代的特点和方法论。 近年来,吴军从技术和管理人员变成了投资人,他对IT领域,尤其是对科技创新因而有了更深入的了解。他根据这些年在硅谷所获得的第一手资料,结合自己的思考,回答了长期以来令大家深感困惑的一个不解之谜,那就是—为什么硅谷在全世界其他地区难以复制? 《硅谷之谜》从某种意义上讲......一起来看看 《硅谷之谜》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

在线进制转换器
在线进制转换器

各进制数互转换器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换