Categories
create-react-app javascript reactjs

Functional component renders once, class component renders twice

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)

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.