My web app has a top navbar that can change in height. It's pinned to the top of the screen, with css position: fixed. To move the page content below it, I have a spacer div, that updates its height to match the height of the header, and pushes everything else down.
I'm updating my app to use React hooks. I have a useLayoutEffect
hook that checks the height of the navbar and updates the height of the spacer to match. Per the React docs:
Unlike componentDidMount or componentDidUpdate, effects scheduled with useEffect don’t block the browser from updating the screen. This makes your app feel more responsive. The majority of effects don’t need to happen synchronously. In the uncommon cases where they do (such as measuring the layout), there is a separate useLayoutEffect Hook with an API identical to useEffect.
What I seem to be finding, is that React lazy loading breaks useLayoutEffect
. Here's a CodeSandBox:
https://codesandbox.io/s/5kqxynp564
There is a div hidden by the navbar, containing the text "IF YOU CAN SEE THIS USELAYOUTEFFECT IS WORKING". When direct import is used, the div above that text is sized to match the navbar, pushing the text down below the navbar, and the text becomes visible. When React.lazy is used, useLayoutEffect
(in AppBarHeader.js) fails to work.
The lazy loading happens in App.js:
//LOADING <COUNTER/> THIS WAY WORKS
// import Counter from "./Counter";
//LAZY LOADING <COUNTER/> THIS WAY BREAKS useLayoutEffect
const CounterPromise = import("./Counter");
const Counter = React.lazy(() => CounterPromise);
What am I misssing?