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,23 +101,27 @@ 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 &&
<ItemWrapper elements.map((element, index) => (
animate={{ <ItemWrapper
animationDelay: `${index * 0.05}s`, style={{
animationDuration: '0.1s', width: debouncedLayout[index]?.width,
transform: `translate(${debouncedLayout[index]?.x}px, ${debouncedLayout[index]?.y}px)`, height: debouncedHeights[index],
width: debouncedLayout[index]?.width, }}
height: heights[index], animate={{
}} animationDelay: `${index * 0.05}s`,
key={index} animationDuration: isInitialRender ? '0s' : '0.1s',
> transform: `translate(${debouncedLayout[index]?.x}px, ${debouncedLayout[index]?.y}px)`,
{element} }}
</ItemWrapper> key={index}
))} >
{element}
</ItemWrapper>
))}
</div> </div>
); );
}; };