2

In the official docs, it says, React will attempt to attach event listeners to the existing markup.
So I thought that if I use ReactDOM.hydrate, it'll only add events.

// server.js
app.get('/', (req, res) => {
    const html = fs.readFileSync(path.resolve('./build/index.html'), 'utf8');

    return res.send(
    html.replace(
      '<div id="root"></div>',
      '<div id="root">hihi</div>',
    ),
  );
}
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

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

// App.jsx
import React from 'react';
import styled from 'styled-components';

export default () => {
  return <Title>Hi !</Title>;
};

const Title = styled.h1`
  color: blue;
`;

However when the hydrate works, it removes DOM created by SSR and replaces it with DOM created by CSR(react script)

enter image description here

Why is this happening?

Jeong Ho Nam
  • 803
  • 12
  • 20

2 Answers2

0

That is not how React SSR works . You should have react at the server side as well and probably you can use renderToString on server side for that. This way react will know this is server rendered react node and needs hydration over client side.

Harish Dhami
  • 1,016
  • 1
  • 7
  • 10
0

Your server rendered HTML is,

<div id="root">
    hihi
</div>

And your client rendered HTML is,

<div id="root">
     <h1 style="color: blue;">Hi !</h1>
</div>

First, the browser loads the server HTML. Then the client starts to rehydrate over the server-rendered HTML which is significantly different compared to client rendered version. Therefore, it removes the hihi text and then adds the h1 element to the DOM. Thats why you see the flickering when you refresh the page. You can change your server HTML as below to fix your issue.

// server.js
app.get('/', (req, res) => {
    const html = fs.readFileSync(path.resolve('./build/index.html'), 'utf8');

    return res.send(
    html.replace(
      '<div id="root"></div>',
      '<div id="root"><h1 style="color: blue;">Hi !</h1></div>',
    ),
  );
}

When you try to do a real project then you need to use ReactDOM.renderToString inside the server side. There are plenty of artcle to get started. Please check this => https://medium.com/bucharestjs/upgrading-a-create-react-app-project-to-a-ssr-code-splitting-setup-9da57df2040a

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43