\$\begingroup\$
\$\endgroup\$
1
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:
- Am I understand right?
- Is there any bad practice?
- 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;
asked Oct 7, 2021 at 9:40
-
\$\begingroup\$ You may find this interesting/useful: overreacted.io/a-complete-guide-to-useeffect \$\endgroup\$RobH– RobH2021年10月07日 13:24:37 +00:00Commented Oct 7, 2021 at 13:24
1 Answer 1
\$\begingroup\$
\$\endgroup\$
4
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
-
\$\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\$Tan Nguyen– Tan Nguyen2021年10月07日 09:57:49 +00:00Commented 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\$Nicky McCurdy– Nicky McCurdy2021年10月07日 10:04:36 +00:00Commented 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\$Tan Nguyen– Tan Nguyen2021年10月08日 10:51:05 +00:00Commented 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\$Nicky McCurdy– Nicky McCurdy2021年10月08日 11:26:44 +00:00Commented Oct 8, 2021 at 11:26
default