Why is my react component rendering twice on initial load?

后端 未结 2 463
抹茶落季
抹茶落季 2021-01-21 01:36

I have a functional component called (First)

function First() {
    const [count,setCount]=useState(0)

    console.log(\"component first rendering\") // this lo         


        
2条回答
  •  一个人的身影
    2021-01-21 02:15

    I've tried this out in code sandbox here and sure enough, it did render twice. This is because, in the index.js file, it uses React.StrictMode.

    According to this documentation:

    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

    • Functions passed to useState, useMemo, or useReducer

    This is usually to help spot side effects only in the development environment. It does not apply to a production environment.

    So if you don't want it to render twice, simply remove the in the index.js file and it'll work normally.

    Hope it helps :)

提交回复
热议问题