airbnb / hypernova-react

React bindings for Hypernova.
https://github.com/airbnb/hypernova
MIT License
248 stars 43 forks source link

Hydrate Component on Client Side Example #42

Closed aftabnaveed closed 6 years ago

aftabnaveed commented 6 years ago

Is there any example available for hydrating a server rendered component on the client side?

aftabnaveed commented 6 years ago

I tried an example today and rendered a component on the server. It seems like my component on the client side does not get re-hydrated and renders again.

import React from 'react';

class Example extends React.Component {

    componentDidMount() {
        console.log('Component Mount on Client Side...');
    }

    render() {
        return(
            <h1>I am an example rendered on Server</h1>
        )
    }
}
export default renderReact('Example', Example);

Above component is successfully rendered on the server, here is its output rendered:

   <div data-hypernova-key="Example" data-hypernova-id="b9002b90-37af-11e8-bd1e-0242ac130005"><h1 data-reactroot="">I am an example rendered on Server</h1></div>
   <script type="application/json" data-hypernova-key="Example" data-hypernova-id="b9002b90-37af-11e8-bd1e-0242ac130005"><!--[]--></script>    </div>
   <script src="http://example.local/js/main.js"></script>
   </body>
   </html>

My client's entry point index.js which is bundled in main.js included above and its content is:

import { renderReact } from 'hypernova-react';
import Example from './bootstrapious/containers/Example';

//import registerServiceWorker from './registerServiceWorker';

renderReact(
    'Example', // this file's name (or really any unique name)
    Example,
);

//ReactDOM.render(<App />, document.getElementById('root'));
//registerServiceWorker();

Problem Although the component is successfully rendered on the server, my component is re-rendred by the client and componentDidMount still gets executed.

Am I missing anything here?

wingleung commented 6 years ago

@aftabnaveed as I understand, that is by design. componentDidMount is not run on the server because only the initial state of the react component is needed, everything after that is not.

On the browser side componentDidMount is run so you can add logic after the mount for some reason. For example, maybe you need some client context data to personalise stuff in the component.

aftabnaveed commented 6 years ago

@wingleung yes it is the expected behaviour and React do run the render method again to attach event listeners etc and calculate mismatches. I am closing this issue now.

Thanks.