Skip to content

Instantly share code, notes, and snippets.

@0ex-d
Created December 11, 2020 10:42
Show Gist options
  • Save 0ex-d/cfc464c2723395c454d792f436fa17c4 to your computer and use it in GitHub Desktop.
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 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