Why does my setInterval run only once in react hooks?

Viewed 2295

Why does this code only triggers the setInterval once and then stops...

const MainBar = ()=> {

  const [clock, setClock] = useState("")

  useEffect(() => {
    const interval = setInterval(setClock(clockUpdate()), 1000);
    console.log('Im in useEffect', clock)
  });

...

Whereas passing it into another function makes it work each second like so ?

const MainBar = ()=> {

  const [clock, setClock] = useState("")

  useEffect(() => {
    const interval = setInterval(()=>{setClock(clockUpdate())}, 1000);
    console.log('Im in useEffect', clock)
  });

...

Sorry I'm new to hooks and javascript.

2 Answers

setInterval requires a function to be passed for it to execute. It will execute the given function every second in this case. () => { setClock(clockUpdate()) } is actually an anonymous function; a function without a name. If you'd give it a proper name, it'd look like function updater() { setClock(clockUpdate()); }.

setInterval(setClock(clockUpdate()), 1000) doesn't work because setClock(clockUpdate()) is already executed, even before it is passed to setInterval. It cannot schedule it to run again, because it's not a function, it is a result already.

You can try this by adding the second parameter in useEffect which means if the clock changes, useEffect will run again

useEffect(() => {
    const interval = setInterval(()=>{setClock(clockUpdate())}, 1000);
    console.log('Im in useEffect', clock)
  }, [clock]);
Related