Skip to content

Commit 490dfaf

Browse files
authored
Read the clock outside render in the purity example
1 parent 15653c0 commit 490dfaf

1 file changed

Lines changed: 3 additions & 5 deletions

File tree

‎src/content/reference/rules/components-and-hooks-must-be-pure.md‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,8 @@ This doesn't mean you shouldn't use non-idempotent functions like `new Date()` _
9191
import { useState, useEffect } from 'react';
9292

9393
function useTime() {
94-
// 1. Keep track of the current date's state. `useState` receives an initializer function as its
95-
// initial state. It only runs once when the hook is called, so only the current date at the
96-
// time the hook is called is set first.
97-
const [time, setTime] = useState(() => new Date());
94+
// 1. Start without a time until the first tick.
95+
const [time, setTime] = useState(null);
9896

9997
useEffect(() => {
10098
// 2. Update the current date every second using `setInterval`.
@@ -110,7 +108,7 @@ function useTime() {
110108

111109
export default function Clock() {
112110
const time = useTime();
113-
return <span>{time.toLocaleString()}</span>;
111+
return <span>{time === null ? 'Loading…' : time.toLocaleString()}</span>;
114112
}
115113
```
116114

0 commit comments

Comments
 (0)