The key difference here is by using the new Date() inside useState(() => new Date())
-> This is called initializer function
, it will avoid recreating the initial state every render.
function Clock() {
const time = new Date(); // 🔴 Bad: always returns a different result!
return <span>{time.toLocaleString()}</span>
}
With this, every time Clock component rendered, the new Date() will create a new object date, React will detect new change causing unnecessary re-render. This may not look like a big issue, but will cause some bottleneck for bigger and more complex component.
Also, please keep in mind that there is a big difference between useState(() => new Date())
and useState(new Date())
.
useState(() => new Date())
is lazy initialing, only when React actually needs the initial state does it call this function. While useState(new Date())
will call new Date() every render.
You can check out more about it on this article: https://react.dev/reference/react/useState#avoiding-recreating-the-initial-state