lightGallery
lightGallery copied to clipboard
React LightGallery component always create a new `LightGallery` instance on re-render
Description
My LightGallery component always create a new LightGallery
instance on each render.

Steps to reproduce
- Use Vite React template.
- Install the library.
- My codes are as below. When
setList()
is called, LightGallery always create a newLightGallery
instance.
const LIGHT_GALLERY_PLUGINS = [lgZoom, lgRotate]
const LIGHT_GALLERY_MOBILE_SETTINGS = {
download: true,
controls: false,
flipHorizontal: false,
flipVertical: false,
rotateRight: false,
}
function MyComponent() {
const [list, setList] = useState([])
return <LightGallery
selector="[data-my-image]"
easing="ease-in-out"
speed={300}
startAnimationDuration={100}
plugins={LIGHT_GALLERY_PLUGINS}
download={true}
mobileSettings={LIGHT_GALLERY_MOBILE_SETTINGS}
enableSwipe={true}
enableDrag={true}
>
{list.map(item => <img key={item.key} data-my-image="" src={item.src} />)}
</LightGallery>
}
Environment
- Browser and version - Edge 106.0.1370.34 arm64
- OS - macOS 12.6
- lightGallery version - 2.6.1
Additional context
I think the bug is related to the usage of restProps
:
// Lightgallery.tsx
// ...
const LG: React.FC<LightGalleryProps> = ({
children,
// ...
onFlipVertical,
...restProps
}: LightGalleryProps) => {
const $lg = React.useRef<HTMLDivElement>(null);
const registerEvents = // ...
React.useEffect(() => {
registerEvents();
const lightGallery = LightGallery(
($lg.current as unknown) as HTMLElement,
restProps,
);
return function cleanup() {
lightGallery.destroy();
};
// ⚠️⚠️⚠️
// Here the reference `resetProps` ALWAYS differ on each render.
// By temporarily removing it, the bug disappears. So a possible solution
// might be manually do a deep check on the properties of `restProps`
// ⚠️⚠️⚠️
}, [registerEvents, restProps]);
return // ...
};
export default LG;
Probably we could use something like react-fast-compare?
Change in effect dependencies has been introduced in 2.6.0, so temporary fix is downgrade to 2.5.0
same the issue. I using inline and it re-render when i update state