I'm trying to create a useEffect in React that starts when the number appears on the screen and it stops once it gets to a certain value (once per website loading).
I found some answers here that use getBoundingClientRect and refs but they are very vague and specific to the other contributors questions.
I created an example for you which creates a counter that starts counting when it becomes visible on the screen, and stops when it reaches a specified value (targetCount). The IntersectionObserver
API is used to detect when the element is visible on the screen. The countRef
is used to refer to the DOM element that needs to be observed. The counter increments every second (1000 milliseconds
) until it reaches the target count.
import React, { useState, useEffect, useRef } from 'react';
const CounterComponent = () => {
const [count, setCount] = useState(0);
const countRef = useRef(null);
const targetCount = 10;
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
let interval = setInterval(() => {
setCount((prevCount) => {
if (prevCount < targetCount) {
return prevCount + 1;
} else {
clearInterval(interval);
return prevCount;
}
});
}, 1000);
}
}, { threshold: 1 });
if (countRef.current) {
observer.observe(countRef.current);
}
return () => {
if (countRef.current) {
observer.unobserve(countRef.current);
}
};
}, []);
return (
<div ref={countRef}>
<h1>{count}</h1>
</div>
);
};
export default CounterComponent;