Search code examples
javascriptreactjsreact-hooksuse-effect

Change text every 3 seconds React useEffect


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>)}

Solution

  • 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.