Created
December 11, 2020 10:42
-
-
Save 0ex-d/cfc464c2723395c454d792f436fa17c4 to your computer and use it in GitHub Desktop.
Using lazy initialization in React.useState https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This example shows how using lazy initialization | |
* in React.useState helps prevent unnecessary computation | |
* Note: There are rare chances you'll need it. | |
*/ | |
const Clock = () => { | |
const [time, setTime] = useState(() => new Date()); // ✅ correct | |
// const [time, setTime] = useState(() => 1000); // ❌ wrong and over-optimization | |
useEffect(() => { | |
const intervalId = setInterval(() => { | |
setTime(new Date()); | |
}, 1000) | |
return () => { | |
clearInterval(intervalId); | |
} | |
}, [tickAmount]); | |
return (<p>The time is {time.toLocaleTimeString()}.</p>); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment