Skip to main content
InterviewHubPRO
Section Overview
Q361

Question 361 of 407

Part 9: React Hooks Deep Dive (262 - 316)

89%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

How to update a component every second?

mid LevelCode ExampleComponentsHooks

You need to use setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.

javascript
    componentDidMount() {
      this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000)
    }

    componentWillUnmount() {
      clearInterval(this.interval)
    }