Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my simple react component print console twice?

Tags:

reactjs

I made a simple components that number state 'a' is increased when the button is clicked.

and I wrote console.log() inside component to check when it is rendered. I expected the console.log is executed once when the button is clicked because component's state is changed.

But, I was wrong and console.log() is executed twice.

Is something wrong? or Is it correct? What i missed?

here is my code

A.jsx

import React, {useState} from 'react';

const A = () => {
    const [a, setA] = useState(0);
    const onClick = () => setA(a + 1);
    console.log('render')

    return (
        <div>
            <p>a : { a}</p>
            <button onClick = {onClick}>button</button>
        </div>
    )
}

export default A;

index.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import A from './components/A';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <A />
  </React.StrictMode>,
  document.getElementById('root')
);

serviceWorker.unregister();

This app is created by CRA with typescript . That's all.

Thanks.

****PLUS******

I checked React dev tools Profiler to check the component is really rendered twice when a button is clicked and state is changed. It show me result below

enter image description here

I think there was only one render. If the component was really rendered once, why the console.log exected twice?

like image 552
Minsik Park Avatar asked Jul 18 '26 21:07

Minsik Park


1 Answers

I think this is because of React.StrictMode this only happens in development. If you remove React.StrictMode you will get only 1 log.

For more details, check this thread on react repo:

https://github.com/facebook/react/issues/15074

On reading further I found this on React docs as well: https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

Hope this helps!

like image 195
Yash Joshi Avatar answered Jul 21 '26 14:07

Yash Joshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!