I came across this simple React functional component, which renders four times, while I would expect it to render once initially, execute the useEffect which updates the state and therefore render again. Instead the console sends 4 log outputs, indicating that it renders four times. Any idea why and any resources on the basic lifecycle of react functional components?
const { useState, useEffect } = React;
function App() {
const [jobs, setJobs] = useState([]);
useEffect(() => setJobs(["test"]), []);
console.log("APP", jobs);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<div>{jobs}</div>
</div>
);
}
ReactDOM.render(
<React.StrictMode>
<App/>
</React.StrictMode>,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.development.js"></script>
https://codesandbox.io/s/solitary-tree-t120d?file=/src/App.js:149-191
This happens because in your codesandbox you use <React.StrictMode>
to wrap your <App />
.
The docs specifically state (https://reactjs.org/docs/strict-mode.html):
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
, andshouldComponentUpdate
methods
....