Reputation: 687
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
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;
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
I think there was only one render. If the component was really rendered once, why the console.log exected twice?
Upvotes: 7
Views: 4624
Reputation: 2784
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!
Upvotes: 14