Get in touch

Send an email to: lammers@gmail.com.
Or find me online at: Github, X

useLayoutEffect and SSR

The useLayoutEffect hook in React fires before the browser repaints the screen. It is useful when we want to get the measurements of DOM elements before rendering. This hook doesn't have any use when rendering on the server (There is no layout information there).

Next.js will show the following warning in the console when trying to use the useLayoutEffect hook in a component that is rendered on the server:

Warning: useLayoutEffect does nothing on the server

To get rid of this warning, we need to make sure that the component with the useLayoutEffect hook only renders on the client:

// Component containing useLayoutEffect
// This should not be rendered on the server
function Child() {
  useLayoutEffect(() => {
    // DOM measurements can be performed here
  });
}

function Parent() {
  const [isMounted, setIsMounted] = useState(false);
  
  // Wait until after client-side hydration to show
  useEffect(() => {
    setIsMounted(true);
  }, []);
  
  return isMounted && <Child />;
}

With Next.js 13 we can simply add the use client at the top of the component file:

`use client`

function Component() {
  // This component will only be rendered on client,
  // so it is safe to use `useLayoutEffect`
  useLayoutEffect(() => {
    // DOM measurements can be performed here
  });
}

React docs on useLayoutEffect
Gist by Dan Abramov