I have this simple bit of code here
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [number, setNumber] = useState(0);
function chaneNumber() {
setNumber(state => state + 1);
}
console.log("here");
return (
<div className="App">
<button onClick={chaneNumber}>Change number</button>
{number}
</div>
);
}
Every time I click the button, I get 2 logs in my console indicating that the component renders twice. I found one post saying this is about strict mode, but I have not enabled strict mode. Why is this component rendering twice on each state update?
Here is a codesandbox link to try it out.
The standard behavior of the useEffect hook was modified when React 18 was introduced in March of 2022. If your application is acting weird after you updated to React 18, this is simply due to the fact that the original behavior of the useEffect hook was changed to execute the effect twice instead of once.
The most straightforward approach to preventing state update re-renders is by avoiding the state update entirely. This means making sure that the setState function is not called unless strictly necessary.
Component re-rendersWhenever a React component uses any state via useState , it will need to be rendered again, or re-rendered, in response to any state change. If a component does not re-render whenever state is updated, it will not be able to display any state updates to the user.
Update in state: The state change can be from a prop or setState change to update a variable(say). The component gets the updated state and React re-renders the component to reflect the change on the app.
Your App component is rendered within React.StrictMode
which is what causes your code to run in strict mode and in strict mode the consoles are shown twice because each function is made to run twice in development mode
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
According to react docs:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With