>

CODEMASTERYLAB

IDE PLATFORM
CoursesCommunity BlogsKnowledge GraphQuizzesInterview Prep

Sign in to track progress & earn XP

Sign In Create Account
>
Code Mastery Lab

Code Mastery Lab

Sign In

Component Lifecycle — Mounting, Updating, and Data Fetching

Question 1 / 1

0:00
Core
Medium

A developer builds a LiveColorCount component that polls an API every 2 seconds and displays the count:

class LiveColorCount extends Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
  }

  componentDidMount() {
    setInterval(() => {
      fetch('/api/colors/count')
        .then(res => res.json())
        .then(({ count }) => this.setState({ count }))
    }, 2000)
  }

  render() {
    return <p>{this.state.count} colors in database</p>
  }
}

After a user navigates away, the server logs show /api/colors/count is still called every 2 seconds indefinitely. What is missing and how do you fix it?