Next.js & React component render twice bug All In One

error ❌

React.StrictMode

https://github.com/facebook/react/issues/15074

https://reactjs.org/docs/strict-mode.html

New Strict Mode Behaviors

https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors

solution ✅

// next.config.js
module.exports = {
-  reactStrictMode: true,
+  reactStrictMode: false,
}

https://nextjs.org/docs/api-reference/next.config.js/react-strict-mode

demos

React 问题复现条件:

  1. state function component 有状态函数组件
  2. state class component 有状态函数组件
  3. hooks component 钩子组件

??? pure react app testing ???

Next.js 问题复现条件:

  1. state function component 有状态函数组件

  2. state class component 有状态函数组件

  3. hooks component 钩子组件

  4. stateless function component 无状态函数组件

  5. stateless class component 无状态函数组件


import React, {
  useEffect,
  useRef,
} from "react";
import { createRoot } from 'react-dom/client';

// export default function Home() {
function Home() {
  const log = console.log;
  log(`v18 createRoot =\n`, createRoot);
  let root = useRef(null);
  useEffect(() => {
    // v18
    console.log(`root =`, root)
    console.log(`root.current =`, root.current)
    if(!root.current) {
      const App = document.getElementById('v18-app');
      root.current = createRoot(App);
      // JSX
      root.current.render(<h1>Develop. Preview. Ship. 🚀 React v18 🆕</h1>);
    }
  }, []);
  return (
    <div id="v18-app">...loading</div>
  )
};

export default React.memo(Home);


/*

Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before.
Instead, call root.render() on the existing root instead if you want to update it.


      // Assignments to the 'root' variable from inside React Hook useEffect will be lost after each render.
      // To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property.
      // Otherwise, you can move this variable directly inside useEffect.eslintreact-hooks/exhaustive-deps
      // https://github.com/facebook/react/issues/14920


*/

refs

https://github.com/web-full-stack/nextjs-ssr/issues/6#issuecomment-1315425580

next.js react components render twice bug ❌

https://deniapps.com/blog/why-the-react-component-renders-twice

https://www.heissenberger.at/en/blog/react-components-reder-twice/

https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


原文地址:http://www.cnblogs.com/xgqfrms/p/16894519.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性