steve238
steve238

Reputation: 1259

How to fix the 'Warning: useLayoutEffect does nothing on the server', when using reactDOMServer.renderToString()?

Using React 17, and MaterialUIv5, with the following code:

const htmlString = reactDOMServer.renderToString(MyReactComponent)

I get the following error in the console:

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See fb.me/react-uselayouteffect-ssr for common fixes.

I need to convert the React Component into a string to pass into a function as a tooltip, is there a better way to do this than to use reactDOMServer.renderToString or reactDOMServer.renderToStaticMarkup?

Upvotes: 0

Views: 478

Answers (1)

Benjamin Cerf
Benjamin Cerf

Reputation: 63

I don't know which MaterialUIv5 component you are using, but it might be because your MyReactComponent includes a useLayoutEffect inside its implementation.

In fact, reactDOMServer.renderToString "produces the initial non-interactive HTML output of your React components" (cf. reactDOMServer.renderToString documentation). Because useLayoutEffect is a "version of useEffect that fires before the browser repaints the screen" (cf. useLayoutEffect documentation), it triggers re-renders that are not supported by renderToString.

Upvotes: 0

Related Questions