useeffect clearinterval loading 1

useeffect clearinterval loading

const Loading = () => {
  const [loadingStatus, setLoadingStatus] = useState(".");

  useEffect(() => {
    const intervalId = setInterval(() => {
      setLoadingStatus(ls => ls + ".");
    }, 1000);

    return () => clearInterval(intervalId);
  }, []);

  return 

{`Loading ${loadingStatus}`}

; };

Here is what the above code is Doing:
1. We’re using the useState hook to create a state variable called loadingStatus and a function to update it called setLoadingStatus.
2. We’re using the useEffect hook to run a function every second.
3. The function we’re running every second is updating the loadingStatus state variable by adding a period to the end of it.
4. We’re returning a paragraph that displays the loadingStatus state variable.

The useEffect hook is a way to run code after a component renders. It’s similar to componentDidMount, componentDidUpdate, and componentWillUnmount combined.

The first argument to useEffect is a function to run after the component renders. The second argument is a list of values that, when changed, cause the useEffect function to run again. If you pass an empty array as the second argument, the useEffect function will only run once.

The useEffect function returns a cleanup function. This cleanup function will run before the useEffect function runs again or before the component unmounts.

In the example above, we’re using the cleanup function to clear the interval that we set up.

The useEffect hook is a great way to handle side effects in function components.

Similar Posts