3

I'm trying to change my text every 3 seconds using useEffect() and setInterval(). Right now it only changes the text ONE time then it doesn't change it anymore. What am i doing wrong?

EDIT: I'm using the library "react-spring"

  const [toggle, setToggle] = useState(false)

  useEffect(() => {
    setInterval(() => {
      switch (toggle) {
        case false: setToggle(true)
        break;
        case true: setToggle(false)
        break;
      }
    }, 3000);
  }, [])

{transitions.map(({ item, props }) => item
  ? <animated.div style={props}>Text that changes #1</animated.div>
  : <animated.div style={props}>Text that changes #2</animated.div>)}
gospecomid12
  • 712
  • 3
  • 11
  • 25
  • You're closing over the `toggle` state inside of your setInterval callback, maybe consider using useInterval hook by Dan: https://overreacted.io/making-setinterval-declarative-with-react-hooks/ (or perhaps a ref). Also worth looking at [this question](https://stackoverflow.com/questions/65489257/react-setinterval-behavior/65489303#65489303) posted yesterday and. its answer – Nick Parsons Dec 30 '20 at 09:21
  • Try something like this instead: `useEffect(() => { setTimeout(() => setToggle(prevToggle => !prevToggle), 3000) }, [toggle]);` the timed out function should get the new toggle value each time – Jayce444 Dec 30 '20 at 09:26
  • It actually worked when i removed the [toggle] in the end of useEffect function. Why is that? I thought that it should listen to toggle variable to work? @Jayce444 – gospecomid12 Dec 30 '20 at 09:34

2 Answers2

6

Solution:

useEffect(() => {
    const intervalID = setInterval(() =>  {
        setToggle((toggle) => !toggle)
    }, 3000);

    return () => clearInterval(intervalID);
}, []);

Important points:

  1. The dependency array [] should be empty. This way you ensure that you're gonna execute this effect only on the initial mounting of the component. You need only a single interval and its creation and destruction are not dependent on a single variable but the component itself. If you put toggle in the dependency array, you will run this effect every time the variable changes thus effectively making YET ANOTHER interval on every 3 seconds. If you did supply a clean-up function, this would still work but it would be more like a setTimeout. However, in your case (without a clean-up function), this will simply introduce infinite number of intervals which will compete with each other.
  2. You have to supply an updater function to setToggle instead of a simple value. This ensures that you're using the most current state for the update and not the stale one in the closure. If you simply provide a value, the interval is making a closure over your initial value and thus updating it. In this way, you will always update the initial false to true and this will repeat forever, leaving you with a "constant" true value.
  3. As you're using an interval, you should provide a clean-up function to the useEffect to clear the interval on component dismount. This is very important as skipping this part will introduce memory leaks and also bugs as you'll try to update a component even after its dismount from the DOM.
zhulien
  • 5,145
  • 3
  • 22
  • 36
0

Try this way

useEffect(() => {
  setTimeout(() => setToggle((prevToggle) => !prevToggle), 3000);
}, [toggle]);
Nooruddin Lakhani
  • 7,507
  • 2
  • 19
  • 39