0

I am working on CSS Transition on React that it automatically unmount after 2 seconds. I am thinking about using useEffect and useState to solve this problem.

I know that changing dependencies inside useEffect causes infinite loop.

For example, the code below will cause infinite loop.

  const [count, setCount] = useState(0);
  useEffect(() => {
    setCount(prev => prev + 1);
  },[count]);

But I think infinite loop won't happen if I set dependency to boolean and set if statement inside useEffect just like the code below.

  const [showStatus, setshowStatus] = useState(false);

  useEffect(() => {
    const timeId = setTimeout(() => {
      if (showStatus === true){
        setshowStatus(false)
      }
    }, 2000)
    return (() => {clearTimeout(timeId)})
  }, [showStatus]);

I am relatively new to React so I am worried about this code. Do I have any problems using this code?

Charo
  • 1

1 Answers1

0

I think it's answered here better

React hooks - right way to clear timeouts and intervals

import { useState, useEffect } from "react";

const delay = 5;

export default function App() {
  const [show, setShow] = useState(false);

  useEffect(
    () => {
      let timer1 = setTimeout(() => setShow(true), delay * 1000);

      // this will clear Timeout
      // when component unmount like in willComponentUnmount
      // and show will not change to true
      return () => {
        clearTimeout(timer1);
      };
    },
    // useEffect will run only one time with empty []
    // if you pass a value to array,
    // like this - [data]
    // than clearTimeout will run every time
    // this value changes (useEffect re-run)
    []
  );

  return show ? (
    <div>show is true, {delay}seconds passed</div>
  ) : (
    <div>show is false, wait {delay}seconds</div>
  );
}
Abdul Mahamaliyev
  • 750
  • 1
  • 8
  • 20