Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my react component rendering twice on initial load?

I have a functional component called (First)

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

    console.log("component first rendering") // this logging is happening twice


    return (
        <div>
            first component
        </div>
    )
}

when i initially run the application the console statement is logging twice why is it, It should have been logged only once, because i haven't explicitily updated the state.

like image 949
user8989 Avatar asked Jun 11 '20 12:06

user8989


1 Answers

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 <React.StrictMode> </ React.StrictMode> in the index.js file and it'll work normally.

Hope it helps :)

like image 58
Sahith Kurapati Avatar answered Oct 12 '22 14:10

Sahith Kurapati