wenzi0github / react

react源码的解析和学习

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

why rerender twice in strict mode and development env?

wenzi0github opened this issue · comments

1

予人玫瑰,手有余香。

前两天我刚帮助其他同学解决了几个问题,面试的时候正好就被问到了,

一个就是当前的这个问题,为什么在测试环境会执行两次;一个就是如何实现一个true和false互相切换的hook。

there is an old saying in China, "gold helps those who to help others".

I have helpd others to solve some React questions, then I received this question in interview.

the one is this question, the other is write a react hook to trigger true and false.

commented

检测意外的副作用

image

在 React.StrictMode 模式下,如果用了 useState,usesMemo,useReducer 之类的 Hook,React 会故意渲染两次,为的就是将一些不容易发现的错误容易暴露出来,同时 React.StrictMode 在正式环境中不会重复渲染。

也就是在测试环境的严格模式下,才会渲染两次。