DEV Community

Cover image for useEffect()
akanoob
akanoob

Posted on

useEffect()

$$useEffect()$$

import { useEffect, useState } from 'react';

export default function ProgressBar(): React.JSX.Element {
    const [time, setTime] = useState(0); // Initializing state for time
    const maxTime: number = 100; // Setting maximum time

    useEffect(() => {
        console.log('SETTING INTERVAL', time); // Log when interval is set up
        const interval = setInterval(() => {
            if (time < maxTime) {
                setTime(prev => prev + 1); // Increment time by 1 if it's less than maxTime
            } else {
                clearInterval(interval); // Clear the interval if time reaches maxTime
            }
        }, 100); // Run the interval every 100 milliseconds

        // Cleanup function for when the component unmounts or the dependency changes
        return () => {
            console.log("end->", time); // Log when the component unmounts or dependency changes
            clearInterval(interval); // Clear the interval to avoid memory leaks
        };
    }, [time]); // Dependency array with 'time', so the effect runs whenever 'time' changes

    return (
        <>
            {/* Render a progress bar with value set to 'time' and maximum value set to 'maxTime' */}
            <progress id='prog' value={time} max={maxTime} />
            {/* Display the percentage value of 'time' */}
            <span>{time}%</span>
        </>
    );
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • useState(0) is used to initialize the state variable time with an initial value of 0. This state variable will keep track of the progress of the progress bar.
  • const maxTime: number = 100; sets the maximum value for the progress bar, in this case, 100.
  • useEffect is a hook that runs side effects in function components. In this case, it sets up an interval to update the progress bar.
  • Inside the useEffect hook:
    • A console.log statement is used to log when the interval is set up.
    • setInterval is used to create a loop that increments the time state variable every 100 milliseconds until it reaches maxTime.
    • If time reaches maxTime, the interval is cleared using clearInterval.
    • The return function is a cleanup function that clears the interval when the component unmounts or when the time state variable changes.
  • The component returns JSX, rendering a <progress> element representing the progress bar. The value attribute is set to the current value of time, and the max attribute is set to maxTime.
  • A <span> element is used to display the percentage value of time.

Top comments (0)