Search code examples
javascriptreactjsapicreate-react-app

Hydrate my React app with HTML from the API instead of static HTML from index.html


I am building a React application using the create-react-app. My application will rely on an API for initial HTML using which I will hydrate my app and add React components to it dynamically during load and serve to the browser.

I planned to call the API in componentDidMount() of the initial app component and replace the static HTML with the dynamic one from the API using ReactDOM.render(element, document) I can replace the whole DOM (including <html></html>).

Is there any other approach which doesn't have a dirty path like this, or is there any other best practices for doing something like this?


Solution

  • If you are using React on the backend then ReactDOM.hydrate is available since React 16.

    Else removing the backend rendered DOM should be preferably done before the first call to ReactDOM.render.