[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.
相关文章
- React saga_react获取子组件ref
- 06-React状态管理 Redux(工作流程, 核心概念, 求和案例, 异步Action, React-Redux, 多状态管理, 纯函数, 高阶函数, Redux开发者工具)
- 07-React Hooks(路由组件懒加载, Context上下文, 组件优化...)
- react基础--3
- 可能你的react函数组件从来没有优化过
- 一小时入门React
- 实现React过程中一次有趣的问题排查经历
- 阿里前端二面高频react面试题
- React 错误边界指南
- react的源码架构
- React渲染机制
- React源码分析--state计算流程和优先级
- 从React源码来学hooks是不是更香呢
- 全新的 React 组件设计理念 Headless UI
- React源码分析7-state计算流程和优先级6
- React为什么不将Vite作为默认推荐?