码迷,mamicode.com
首页 > 其他好文 > 详细

[React] Avoiding state flickers

时间:2020-03-08 10:00:45      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:default   bsp   more   https   ror   and   nbsp   tutorial   oca   

As a user, it can be very disorienting when the "wrong" UI is briefly shown to the user: a login link is shown to an authenticated user, or a 404 error flashes before the page loads correctly. This issue is common in Gatsby applications, because of how Gatsby pre-builds HTML files.

In this video, we show how issues like this can slip through, and how we can solve the problem by skipping user-specific state during the build. Instead, we‘ll leave that spot blank, and fill it in later on the client, when we know what should go there.

While this tutorial uses Gatsby, the same lesson can be applied to Next.js, or any server-rendered React application.

Learn more about the nitty-gritty in this blog post

 

import React from react;

const ClientOnly = ({ children }) => {
  const [
    hasMounted,
    setHasMounted,
  ] = React.useState(false);

  React.useEffect(() => {
    setHasMounted(true);
  }, []);

  if (!hasMounted) {
    return null;
  }

  return children;
};

export default ClientOnly;

 

Problem for flicker:

We fetch the state from backend or localstorage, so during the first render, our applciation might render a default state, after response coming back, we render another state. it causes flicker.

The tick is ‘‘useEffect‘ runs after every rendering including the first, so after first render, we set ‘hasMounted‘ to true. So for the first rendering, it return ‘null‘ to prevent rendering anything to the screen.

 

[React] Avoiding state flickers

标签:default   bsp   more   https   ror   and   nbsp   tutorial   oca   

原文地址:https://www.cnblogs.com/Answer1215/p/12440517.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!