0
\$\begingroup\$

I am learning about hooks, so I try to write code that display current time.

I had comment in each line of code the reason I write it. So:

  1. Am I understand right?
  2. Is there any bad practice?
  3. What need to be improved?
import * as React from 'react'
function App() {
 // Define a state for keeping track of time
 const [time, setTime] = React.useState("");
 // Logic, computation to update time (which is side-effect) should put inside useEffect
 React.useEffect(() => {
 // Running side-effect when component mounted (componentDidMount)
 const myInterval = setInterval(() => {
 setTime(new Date().toLocaleTimeString());
 }, 1000);
 // Clear side-effect when component unmount (componentWillUnmount)
 return () => {
 clearInterval(myInterval);
 }
 })
 return (
 <div className="App">
 <h1>{time}</h1>
 </div>
 );
}
export default App;
Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked Oct 7, 2021 at 9:40
\$\endgroup\$
1

1 Answer 1

3
\$\begingroup\$

By default, useEffect will run on every render. Because you're setting state in useEffect, state will render on every render, causing loops of unnecessary renders.

To fix this, pass an empty dependency array to useEffect:

React.useEffect(() => {
 // ...
}, [])
answered Oct 7, 2021 at 9:49
\$\endgroup\$
4
  • \$\begingroup\$ What is the loops look like? I inspect the page and see blue border blinking (render) 1 time/s only. I add [] and things are the same too. \$\endgroup\$ Commented Oct 7, 2021 at 9:57
  • \$\begingroup\$ Basically it will add a new listener that updates state an extra time every second. So after 10 seconds, it will render 10 times at once. That's probably not what you want, especially if this component gets more complex in the future. \$\endgroup\$ Commented Oct 7, 2021 at 10:04
  • \$\begingroup\$ What do you think about this argument: "useState only fires if the the value you are updating the state with is different to the previous one so an infinite loop is prevented unless the value changes between cycles." stackoverflow.com/questions/53715465/… \$\endgroup\$ Commented Oct 8, 2021 at 10:51
  • \$\begingroup\$ That doesn't apply here in your original code because it has no dependencies. By definition it will run on every render regardless of your state. \$\endgroup\$ Commented Oct 8, 2021 at 11:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.