简体   繁体   中英

Why does react re-render twice when using the state hook (useState)?

I have created a component, App , based on reactjs's example of the state hook useState . Here is my code:

import React, { useState } from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  console.log("before");
  const [count, setCount] = useState(0);
  console.log("after");

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count+1)}>
        Click me
      </button>
    </div>
  );
}

export default App;

When I run this using node, App renders a button on http://localhost:3000/ :

在此处输入图片说明

Based on the explanation accompanying the reactjs example (link above), I would expect that clicking the button would cause App to be re-rendered one time. However, clicking (once) actually causes the re-render to occur twice:

在此处输入图片说明

Why does this example lead to the re-render occurring twice?

How can I correct this so that does not occur more than necessary?


Note: With each click, two new lines of each 'before' and 'after' are printed to the console, so the double-rendering appears to occur with each click, not due to the initial render.

What you're seeing is the first 'before' and 'after' is from the initial render and the second pair is from when you click the button and state is updated.

It seems the offending code comes from <React.StrictMode>

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

Removing the <React.StrictMode> gets rid of this issue.

ReactDOM.render(<App />, document.getElementById('root'));

在此处输入图片说明 安慰

Further Reading: React Components rendered twice — any way to fix this?

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