useLayoutEffect and SSR

How to get warning free usage of useLayoutEffect when server-side rendering

Photo by Caleb George on Unsplash
function App() {
useLayoutEffect(() => {
console.log("layout effect");
});
return "hello world";
}
// Will log a warning
const html = ReactDOMServer.renderToString(<App />);

A workaround (hack)

// use-isomorphic-layout-effect.jsimport { useLayoutEffect, useEffect } from 'react';const useIsomorphicLayoutEffect =
typeof window !== 'undefined' ? useLayoutEffect : useEffect;
export default useIsomorphicLayoutEffect;
// app.js
import useLayoutEffect from './use-isomorphic-layout-effect';
function App() {
useLayoutEffect(() => {
console.log('hello there');
}, []);
return 'Hello world';
};

eslint

import { useLayoutEffect, useEffect } from 'react';const useIsomorphicLayoutEffect =
typeof window !== 'undefined' ? useLayoutEffect : useEffect;
// Ensure the name used in components is useLayoutEffect
export default { useLayoutEffect: useIsomorphicLayoutEffect };
module.exports = {
// other config ...
rules: {
'no-restricted-imports': [
'error',
{
// Disabling using of useLayoutEffect from react
{
name: 'react',
importNames: ['useLayoutEffect'],
message:
'`useLayoutEffect` causes a warning in SSR. Use `useIsomorphicLayoutEffect`',
},
],
},
],
'no-restricted-syntax': [
'error',
// Ensure import from '*use-isomorphic-layout-effect' is `useLayoutEffect` to leverage `eslint-plugin-react-hooks`
{
selector:
'ImportDeclaration[source.value=/use-isomorphic-layout-effect/] > ImportDefaultSpecifier[local.name!="useLayoutEffect"]',
message:
'Must use `useLayoutEffect` as the name of the import from `*use-isomorphic-layout-effect` to leverage `eslint-plugin-react-hooks`',
},
],
}
}

Summary

--

--

JavaScript enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store