IntersectionObserver Flickering with ScrollIntoView

Viewed 150

I'm trying to build a custom input that you can change its value by scrolling with IntersectionObserver and ScrollIntoView

The problem that I'm facing is that when I try to make the component controlled with a state it starts to flicker when scrolling.

I have the example here in this sandbox, and you can see the input gets initialized correctly with the correct value, but when you try to change it.. there is a flickering at the beginning of the scroll event. also resetting the input by the button does seem to work correctly.

I'm not really able to figure out how to get the updates correctly done in each event since I'm very new to Intersection observer

2 Answers

Try setting the threshold value to 1 such that it will fire only when it goes out of boundary completely.

const observer = new IntersectionObserver(
      (entries) => {
        const selectedEntry = entries.find(
          (e) => Number.parseFloat(e.target.textContent) === value
        );

        selectedEntry?.target?.scrollIntoView();

        entries.forEach((entry) => {
          if (!entry.isIntersecting) {
            return;
          }

          !isFirstRender &&
            onChange(Number.parseFloat(entry.target.textContent));
        });
      },
      { threshold: 1 } // changed to 1
    );

Also please do as the linter says, and add proper dependencies for the useEffect hook unless when not needed.

Related