Misuti
Misuti

Reputation: 323

Gatsby 1 Class Component

I'm trying to understand the logic of this component called AppMounted in a layout (Gatsby 1)

import { Component } from 'react';

export default class AppMounted extends Component {
  componentDidMount() {
    /* eslint-disable no-undef */

    // If the body element does not yet contain the "app-mounted" class
    if (!document.body.classList.contains('app-mounted')) {
      // Wait just a little longer
      setTimeout(() => {
        // And then add it
        document.body.classList.add('app-mounted');
      }, 50);
    }
    /* eslint-enable no-undef */
    // 50
  }

  render() {
    return null;
  }
}

and then scss style for body

body {
    visibility: hidden;
        &.app-mounted {
            visibility: visible;
       }
}

From my understanding is that this wait for all 50ms for the components/data to load then display them. But without this component everything also works perfectly. The problem is it is causing trouble on Gastby 2 and hides everthing. By taking it out on the Gastby 2 version, everything works again. Is there any reason why one would need to hide the body and then display it again?

Any feedback would be appreciated, thank you!

Upvotes: 0

Views: 64

Answers (1)

coreyward
coreyward

Reputation: 80090

This component appears to be trying to avoid a flash of unstyled content while the page loads. There's certainly nothing about Gatsby v2+ that would require this sort of pattern to be utilized. All of your React components render server-side and are rehydrated on the client.

I'd strongly advise against using this type of pattern. If JavaScript doesn't execute nothing is visible. If the client is slow and React takes a while to rehydrate client-side, the componentDidMount call would be delayed far more than the 50ms included in the timeout. On subsequent visits to the page, the component will re-mount even though all assets are likely cached, resulting in a needless delay. And so on.

Upvotes: 1

Related Questions