0

I am a beginner in React and I am learning it from a udemy course. Initially I thought the whole code inside the functional component gets re rendered/re run after state update. But then I saw this implementation of countdown before redirect and got confused.

import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";

const LoadingToRedirect = () => {

  const [count, setCount] = useState(5);
  let history = useHistory();

  useEffect(() => {
    const interval = setInterval(() => {
      setCount((currentCount) => --currentCount);
    }, 1000);

    // redirect once count is equal to 0

    count === 0 && history.push("/");

    // cleanup

    return () => clearInterval(interval);

  }, [count]);

  return (
    <div className="container p-5 text-center">
      <p>Redirecting you in {count} seconds</p>
    </div>
  );
};

export default LoadingToRedirect;

So why is setInterval needed here if setCount triggers a re-render of the whole code? Can't we do the same thing with setTimeout? So I tried that and it worked. Surely there is a reason he did it that way? Am I missing something?

anandsr-dev
  • 67
  • 2
  • 5
  • 1
    `Can't we do the same thing with setTimeout?` Yes you can, and given that `count` is used as a dependency for the effect, the interval is quite pointless. – tkausl Oct 10 '21 at 14:25
  • 1
    Does this answer your question? [react hooks and setInterval](https://stackoverflow.com/questions/53981593/react-hooks-and-setinterval) – Nizar Oct 10 '21 at 14:34

1 Answers1

0

Of course React re-renders the whole component but it also depends on some conditions. For example if you look at your code you have passed count variable as a dependency to useEffect hook, it means if the value of count changes React will render the effect inside of the useEffect hook.

Yes, you can achieve the same using setTimeout;setInterval is pointless because it totally depends on count variable you passed as a dependency.

if you remove count as a dependency then you can easily see it will not redirect you the required page.

Gulshan Aggarwal
  • 954
  • 1
  • 7
  • 13