简体   繁体   中英

Why is react component function executed even when the state variable value is not changed?

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?

Every time the button is clicked, the state is set. Even tho it is being set to the same string, the state is still changing and thus causing that component to re-render. This is why you are seeing the console log every time the button is clicked.

useState doesn't have its own memoization built-in. As you are setting the state to the same string on the button click, look into memoization in react. This should solve this problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM