[React] Avoiding state flickers

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.

 

posted @   Zhentiw  阅读(98)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-03-08 [Node.js] Load balancing a Http server
2019-03-08 [Node.js] Child Process with fork() to handle heavy calculation process
2019-03-08 [Algorithm] Write your own Math.pow function in Javascript, using Recursive approach
2019-03-08 [Functional Programming] Fst & Snd, Code interview question
2019-03-08 [React GraphQL] Pass Parameters to urql's useQuery React Hook
2019-03-08 [Algorithm] Find first missing positive integer
2018-03-08 [HTML5] Accessibility Implementation for complex component
点击右上角即可分享
微信分享提示