I've encountered an unusual flickering glitch that only occurs when using the combination of:
- css scroll-snap
- useState
- Sub-Components
But it's strange because the issue only arises when these three are combined!
https://i.sstatic.net/TvwyW.gif
Here is a simplified version of the problematic code:
carousel.js
import styles from './carousel.module.scss'
import { useEffect, useRef, useState } from 'react';
export default function Carousel() {
const [currentScollPos, setCurrentScrollPos] = useState(0)
const carouselRef = useRef()
useEffect(() => {
const carouselScrollUpdate = (e) => {
setCurrentScrollPos(e.target.scrollLeft)
}
carouselRef?.current?.addEventListener('scroll', carouselScrollUpdate, { passive: true })
return () => {
carouselRef?.current?.removeEventListener('scroll', carouselScrollUpdate, { passive: true })
}
}, [carouselRef])
const Slide = () => <div className={styles.carouselSlide}>Test Sub</div>
return (
<div className={styles.carouselInnerContainer} ref={carouselRef}>
<div className={styles.carouselSlide}>Test1</div>
<div className={styles.carouselSlide}>Test2</div>
<div className={styles.carouselSlide}>Test3</div>
<Slide />
</div>
)
}
carousel.module.scss
.carouselInnerContainer {
display: flex;
flex-wrap: nowrap;
overflow-x: scroll;
scroll-snap-type: x mandatory;
}
.carouselSlide {
flex: 0 0 auto;
width: 50%;
margin-left: 2rem;
background-color: aquamarine;
height: 200px;
scroll-snap-align: center;
}
The flickering issue will NOT occur if I do ONE of the following:
- comment out:
setCurrentScrollPos(e.target.scrollLeft)
- comment out:
<Slide />
- comment out:
scroll-snap-align: center;
in the CSS
Any insights on this peculiar behavior?