I know it just renders HTML as text, so speaking of class components, only contructor() and render() methods are invoked during the renderToString(). But I've noticed some weird behavior with regards to function components. Consider the following component example:
function MyComponent() {
console.log(1);
return(
<React.Fragment>
Some text
</React.Fragment>
)
}
I just use console.log() inside of function component, which, I guess, is equivalent to constructor() method inside of a class component.
renderToString() is invoked inside express route handler:
import { ServerStyleSheets, ThemeProvider } from '@material-ui/core/styles';
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import theme from 'mui/theme';
import App from 'components/App';
const SERVER_PORT = 8081; // Port for Express to listen
const app = express();
app.get('*', async (req, res) => {
const sheets = new ServerStyleSheets();
const inlineApp = renderToString(
sheets.collect(
<Provider store={exampleStore}>
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
</ThemeProvider>
</Provider>,
),
);
const css = sheets.toString();
const renderedHTML = `
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style id="jss">${css}</style>
<title>Repl.it</title>
</head>
<body>
<div id="root">${inlineApp}</div>
<script>
window.STATE = ${JSON.stringify(exampleStore.getState())};
</script>
<script src="app.js"></script>
</body>
</html>
`;
res.send(renderedHTML);
});
app.listen(SERVER_PORT, () => {
console.log(`Listening at http://localhost:${SERVER_PORT}`);
});
The problem is I'm getting the console output twice when invoking ReactDOMServer.renderToString() once. I dont use double rendering on server side.
So I have two questions:
Can you explain what's exactly happening here?
If it is a correct behavior, then is there a way to run some code only once during the
renderToString()?