4

I have a function react component that has a counter that starts from 10000 and goes to 0.

I am setting a setInterval callback using useEffect hook during component mounting. The callback then updates the counter state.

But I don't know why, the count value never decreases. Each time the callback runs count is 10000.

(I am using react & react-dom version 16.8.3)

Function component is as below:

import React, { useState, useEffect, useRef } from 'react'

const Counter = () => {
  const timerID = useRef()
  let [count, setCount] = useState(10000)

  useEffect(() => {
    timerID.current = setInterval(() => {
      //count here is always 10000
      if (count - 1 < 0) {
        setCount(0)
      } else {
        setCount(count - 1)
      }
    }, 1)
  }, [])

  return <h1 className="counter">{count}</h1>
}

export default Counter

Here is the link to codesandbox: link

4
  • setState() is asynchronous... Commented Apr 7, 2019 at 20:25
  • Don't think that matters here. Commented Apr 7, 2019 at 20:29
  • setCount(--count ) works. May or may not be best approach?? It's a closure issue Commented Apr 7, 2019 at 20:31
  • set count as a dependency and use setTimeout will solve your pains :). because the next time rendering setTimeout will be called again when count has a new value Commented Apr 7, 2019 at 21:09

3 Answers 3

5

You need to watch for changes in count, and also clean up your useEffect():

useEffect(() => {
    timerID.current = setInterval(() => {
      if (count - 1 < 0) {
        setCount(0)
      } else {
        setCount(count - 1)
      }
    }, 100)

    return () => clearInterval(timerID.current);
  }, [count])

As @Pavel mentioned, Dan Abramov explains why here.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi @Colin, Wouldn't that set new interval every time count is updated? I don't want this to happen. setInterval() should setup only once during mounting.
Yes it will. If you look at the blog post, there's a suggested useInterval hook which does a similar but more complex thing. TLDR; you need to set up and clear the interval on each re-render but it shouldn't be an expensive operation.
Got it!! Wondering how could I not find that blog post while searching for this on google... ><) Thanks anyway:) For now, I will go with using the "updater" form solution as mentioned in that post.
2

There are 2 options:

1) Include count in the dependencies

This is not ideal, as it means a new setInterval will be created on every change of count, so you would need to clean it up on every render, example:

  useEffect(() => {
    timerID.current = setInterval(() => {
      //count here is always 10000
      if (count - 1 < 0) {
        setCount(0)
      } else {
        setCount(count - 1)
      }
    }, 1)
    return () => clearInterval(timerID.current) // Added this line
  }, [count]) // Added count here

2) Add the count in the setInterval callback function.

This is the best approach for intervals, as it avoids, setting new ones all the time.

 useEffect(() => {
    timerID.current = setInterval(() => {
      // count is used inside the setCount callback and has latest value
      setCount(count => {
        if (count - 1 < 0) { // Logic moved inside the function, so no dependencies
          if (timerID.current) clearInterval(timerID.current)
          return 0
        }
        return count - 1
      })
    }, 1)
    return () => {
      if (timerID.current) clearInterval(timerID.current) // Makes sure that the interval is cleared on change or unmount
    }
  }, [])

Here is the sandbox link

Comments

1

You are declaring effect function when component mount as you said. So in scope in that time value store inside count is equal to 10000. That means every time interval function executes it takes count value from closure (10000). It is actually pretty tough to do it correctly. Dan wrote whole blog post about it

1 Comment

Got it!! Wondering how could I not find that blog post while searching for this on google... ><) Thanks anyway:)

Your Answer

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.