Why is my react component rendering twice on initial load?

后端 未结 2 459
抹茶落季
抹茶落季 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 01:58

    This is happening because your App is wrapped under React.StrictMode.

    
    
    
    

    Strict mode is introduced for functional components in React 16.*. We wrap our component under React.StrictMode to identify the potential errors in our application.

    StrictMode helps to maintain stability of large codebases and helps in up-gradation to newer versions of React. StrictMode logs errors in console for the issues which our application can have:

    React.StrictMode needs to trigger some methods and lifecycle hooks twice to resolve these problems:

    1. These are methods which might be called more then once and can have side effects, so React.StrictMode trigger these methods twice to check any side effect. If there is any sideeffect, the error will be logged. (side effect: Things which are updated outside the method/component)

      • constructor
      • componentWillMount (or UNSAFE_componentWillMount)
      • componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)
      • componentWillUpdate (or UNSAFE_componentWillUpdate)
      • getDerivedStateFromProps
      • shouldComponentUpdate
      • render
      • setState updater functions (the first argument)
    2. There are possibilities that we are using some old React methods and APIs, So React.StrictMode identifies that and log the error to console mentioning, the method is outdated.

    3. React.StrictMode works only in development mode, so no need to worry for production.

    Conclusion: React.StrictMode is provided by React community to help our applications keep track of changes and we can easily upgrade our applications to new versions with Confidence.

提交回复
热议问题