The following code prints out the same time twice inside the console of codesandbox.io website (that version uses StrictMode
) and also in the snippet below (not using StrictMode
):
const { useState, useEffect } = React;
function useCurrentTime() {
const [timeString, setTimeString] = useState("");
useEffect(() => {
const intervalID = setInterval(() => {
setTimeString(new Date().toLocaleTimeString());
}, 100);
return () => clearInterval(intervalID);
}, []);
return timeString;
}
function App() {
const s = useCurrentTime();
console.log(s);
return <div className="App">{s}</div>;
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.development.js"></script>
Demo: https://codesandbox.io/s/gallant-bas-3lq5w?file=/src/App.js (using StrictMode
)
Here's a snippet using production libs; it still logs twice:
const { useState, useEffect } = React;
function useCurrentTime() {
const [timeString, setTimeString] = useState("");
useEffect(() => {
const intervalID = setInterval(() => {
setTimeString(new Date().toLocaleTimeString());
}, 100);
return () => clearInterval(intervalID);
}, []);
return timeString;
}
function App() {
const s = useCurrentTime();
console.log(s);
return <div className="App">{s}</div>;
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
However, when I open up the Developer's Console, I see each time printed out only once, and also in the codesandbox.io's console, I see it printed once.
And then if I create a standalone React app using create-react-app, and use the above code, and each time is printed twice.
How is this behavior understood, for printed out once or twice depending on different situations? My thinking was, if the state changes, then App
is re-rendered, with that new string, once, so it is printed out once. What is strange is especially why does it printed out twice but when Dev Console is open, then it is once?