ChristophP / web-react-components

Reuse your react components, for example in Elm or any other technology by wrapping them easily into a Web Component.
58 stars 5 forks source link

React component render multiple times #45

Open ppiyush13 opened 4 years ago

ppiyush13 commented 4 years ago

Thanks for creating awesome library. This has really saved my time.

I want to bring to your notice that the wrapped React component is getting rendered multiple times initially. To be exact it re-renders as many times as many attributes listening on.

Here is the code snippet which reproduces this issue:

import React from 'react;
import { register } from 'web-react-components';

const SimpleComponent = props => {
    console.log(props);

    return <div>Simple Component</div>
};

register(SimpleComponent, 'simple-component', [
    'prop1', 'prop2', 'prop3', 'prop4',
]);

Above component is used as below

<simple-component prop1="A" prop2="B" prop3="C" prop4="D"></simple-component>

I managed to debug the code and my observation is attributeChangedCallback rendering the react component again https://github.com/ChristophP/web-react-components/blob/master/src/index.js#L206. Initially attributeChangedCallback is called for every attribute then finally connectedCallback is called.

We can add condition in attributeChangedCallback to re-render only once connectedCallback has been called. Something like this


   constructor() {
      super();
      if (options.useShadowDOM) {
        this.attachShadow({ mode: "open" });
      }
      this.renderOnAttrChange = false;
    }

    connectedCallback() {
      render(this);
      this.renderOnAttrChange = true;
    }

    attributeChangedCallback() {
      if(this.renderOnAttrChange)
          render(this);
    }