$$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>
</>
);
}
Explanation:
-
useState(0)is used to initialize the state variabletimewith 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. -
useEffectis a hook that runs side effects in function components. In this case, it sets up an interval to update the progress bar. - Inside the
useEffecthook:- A
console.logstatement is used to log when the interval is set up. -
setIntervalis used to create a loop that increments thetimestate variable every 100 milliseconds until it reachesmaxTime. - If
timereachesmaxTime, the interval is cleared usingclearInterval. - The return function is a cleanup function that clears the interval when the component unmounts or when the
timestate variable changes.
- A
- The component returns JSX, rendering a
<progress>element representing the progress bar. Thevalueattribute is set to the current value oftime, and themaxattribute is set tomaxTime. - A
<span>element is used to display the percentage value oftime.
Top comments (0)