Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  121] [ 7]  / answers: 1 / hits: 5270  / 3 Years ago, wed, december 30, 2020, 12:00:00

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

More From » reactjs

 Answers
11

Solution:


useEffect(() => {
const intervalID = setTimeout(() => {
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.


[#2040] Wednesday, December 23, 2020, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
martina

Total Points: 101
Total Questions: 103
Total Answers: 111

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;