Skip to content

Commit

Permalink
[Masonry] Fix flickering when used with React 18
Browse files Browse the repository at this point in the history
  • Loading branch information
mnajdova committed Jun 15, 2022
1 parent c3af5ef commit 42fdc5e
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions packages/mui-lab/src/Masonry/Masonry.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { unstable_composeClasses as composeClasses } from '@mui/base';
import { flushSync } from 'react-dom';
import { styled, useThemeProps } from '@mui/material/styles';
import {
createUnarySpacing,
Expand Down Expand Up @@ -245,9 +246,13 @@ const Masonry = React.forwardRef(function Masonry(inProps, ref) {
}
});
if (!skip) {
setMaxColumnHeight(Math.max(...columnHeights));
const numOfLineBreaks = currentNumberOfColumns > 0 ? currentNumberOfColumns - 1 : 0;
setNumberOfLineBreaks(numOfLineBreaks);
// In React 18, state updates in a ResizeObserver's callback are happening after the paint which causes flickering
// when doing some visual updates in it. Using flushSync ensures that the dom will be painted after the states updates happen
// Related issue - https://github.com/facebook/react/issues/24331
flushSync(() => {
setMaxColumnHeight(Math.max(...columnHeights));
setNumberOfLineBreaks(currentNumberOfColumns > 0 ? currentNumberOfColumns - 1 : 0);
});
}
};

Expand Down

0 comments on commit 42fdc5e

Please sign in to comment.