React Components rendered twice — any way to fix this?

A) Functional Component with useState

function App() {
const [click, setClick] = React.useState(0);
console.log('I render 😡', click);
return (
<div>
<button onClick={() => setClick(click => click + 1)}>
Clicks: {click}
</button>
</div>
)
}
I render 😡 0
I render 😡 0
I render 😡 1
I render 😡 1
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
I render 😡 0
I render 😡 1

B) Functional Component with useReduce

function App() {
const [clicks, dispatch] = React.useReducer((state, action) => {
switch (action.type) {
case 'click':
return state + 1;
default:
throw new Error()
}
}, 0)
console.log('I render 😡', clicks);
return (
<div >
<button onClick={()=>dispatch({type:'click'})}>
Clicks: {clicks}
</button>
</div>
)
}
I render 😡 0
I render 😡 0
I render 😡 1
I render 😡 1

C) Class Component

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

What is happening behind the scenes?

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

Why should I use React.StrictMode?

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andreas Heissenberger

Andreas Heissenberger

Fast-track professional successful in the design, development and deployment of technology strategies and policy. Experienced leading Internet and IS operations