Why does useState cause the component to render twice on each update?

后端 未结 1 403
南方客
南方客 2020-11-22 14:46

I have this simple bit of code here

import React, { useState } from \"react\";
import \"./styles.css\";

export default function App() {
  const [number, set         


        
相关标签:
1条回答
  • 2020-11-22 15:07

    Your App component is rendered within React.StrictMode which is what causes your code to run in strict mode and in strict mode the consoles are shown twice because each function is made to run twice in development mode

    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      rootElement
    );
    

    According to react docs:

    Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

    • Class component constructor, render, and shouldComponentUpdate methods
    • Class component static getDerivedStateFromProps method
    • Function component bodies
    • State updater functions (the first argument to setState)
    • Functions passed to useState, useMemo, or useReducer
    0 讨论(0)
提交回复
热议问题