Understanding Double Renders in useState
In React, the useState hook is commonly used to manage component state. However, under certain conditions, you may notice that a component rendered with useState renders twice for each state update. This behavior has confounded many developers who have not enabled Strict Mode. Why does this occur?
The Role of Strict Mode
Contrary to the assumption that Strict Mode is not enabled, your code is actually running under its constraints. By default, modern versions of React implicitly wrap the outermost component in a
Double Function Invocation in Strict Mode
React's documentation explicitly states that Strict Mode intentionally "double-invokes" certain functions, including the state updater functions passed to setState and useState. This means that whenever you call setNumber in your code, it is being invoked twice.
Consequences of Double Invocation
This double invocation leads to the component being rendered twice. This behavior is intended to help developers spot potential side effects by making them more deterministic. By default, React defer updates when using the useState hook. However, Strict Mode bypasses this behavior, causing the rendering to occur twice.
Conclusion
In summary, the double rendering of components using useState is a consequence of running your code under React's Strict Mode. While it may seem unexpected, this behavior is intentional and designed to enhance debugging capabilities by making side effects more apparent.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3