I used npx create-react-app
to create a react app. Following are the index.js and App.js code:
Index.js (did not use StrictMode)
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
App.js
import {useState} from 'react';
function App() {
console.log('App component function executed');
const [name, setName] = useState('name');
const changeNameHandler = () => {
setName('newname');
}
return (
<div className="App">
{name}
<button onClick={changeNameHandler}>Change Name</button>
</div>
);
}
export default App;
When I start the app I see 'App component function executed' in the console for the first time which is expected. Then I click the 'Change Name' button and see another 'App component function executed' in the console, still expected.
At this point the state has been set to 'newname' so when I click the button again, new message should not be logged in the console, but it again consoles 'App component function executed'. Clicking the button further doesn't do anything.
I expected that 'App component function executed' would be logged only 2 time (first at initial mounting and when the button is clicked the first time). Or it would be logged every time I click the button. But I see it logging exactly 3 times.
Can someone explain this behavior?