8

So, I started this new project with create-react-app (it's running react v.16.13.1). I rewrote the base App component as a class, and I found that when the component is a function, like this:

function App() {
  console.log('App (function)');
  return 'App (function)';
}

the browser console prints out

App (function)

Great, thanks! But if the same App component is written as

class App extends React.Component {
  render() {
    console.log('App (class)');
    return 'App (class)';
  }
}

console writes

App (class)
App (class)
freshdevelop
  • 155
  • 11
  • Does this answer your question? [Why is my React component is rendering twice?](https://stackoverflow.com/questions/48846289/why-is-my-react-component-is-rendering-twice) – keikai Apr 02 '20 at 06:56
  • 1
    The point is, I'm not touching the state yet (I know that state changes naturally trigger re-rendering of the component). What I'm not getting is why these two procedures differ, aren't they basically the same thing? – freshdevelop Apr 02 '20 at 07:01
  • It's been clearly written in the official document, kindly check it would solve the question you are facing. – keikai Apr 02 '20 at 07:07

1 Answers1

17

In recent versions of react, rendering uses strict mode when running in development. Strict mode intentionally double-calls the constructor and render functions to better detect unexpected side effects.

From the docs (emphasis is mine):

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

Based on that I'd also expect the function component to render twice, which we don't see happening, but React might be being smart about it since there's no state.

In my testing, running in production mode did not result in the same double render of the class component.

Cameron Little
  • 3,487
  • 23
  • 35