fix: improved render performance on masonry

This commit is contained in:
Morten Olsen
2023-06-16 14:34:51 +02:00
parent c11d5248ff
commit 6fceea9269

View File

@@ -77,6 +77,16 @@ const Masonry = ({ children }: Props) => {
setColumnWidth(nextColumnWidth); setColumnWidth(nextColumnWidth);
}, []); }, []);
const isInitialRender = useMemo(
() =>
!!(
columnWidth === 0 ||
heights.length !== elements.length ||
heights.find((height) => height === undefined)
),
[heights, elements, columnWidth],
);
useLayoutEffect(() => { useLayoutEffect(() => {
if (!ref.current) { if (!ref.current) {
return; return;
@@ -91,17 +101,21 @@ const Masonry = ({ children }: Props) => {
}, [updateSize]); }, [updateSize]);
const debouncedLayout = useDebounce(layout, 10); const debouncedLayout = useDebounce(layout, 10);
const debouncedHeights = useDebounce(heights, 10);
return ( return (
<div ref={ref}> <div ref={ref}>
{elements.map((element, index) => ( {columnWidth > 0 &&
elements.map((element, index) => (
<ItemWrapper <ItemWrapper
style={{
width: debouncedLayout[index]?.width,
height: debouncedHeights[index],
}}
animate={{ animate={{
animationDelay: `${index * 0.05}s`, animationDelay: `${index * 0.05}s`,
animationDuration: '0.1s', animationDuration: isInitialRender ? '0s' : '0.1s',
transform: `translate(${debouncedLayout[index]?.x}px, ${debouncedLayout[index]?.y}px)`, transform: `translate(${debouncedLayout[index]?.x}px, ${debouncedLayout[index]?.y}px)`,
width: debouncedLayout[index]?.width,
height: heights[index],
}} }}
key={index} key={index}
> >