How to fix: "Warning: useLayoutEffect does nothing on the server"

Published on

Photo by Davide Manzini on Unsplash

The "useLayoutEffect does nothing on the server" occurs when we call useLayoutEffect on the server side, for example in Next.js.

This warning happens because useLayoutEffect() only fires after DOM mutations. Looking also at the official react docs they mentions:

If you use server rendering, keep in mind that neither useLayoutEffect nor useEffect can run until the JavaScript is downloaded. This is why React warns when a server-rendered component contains useLayoutEffect.

To solve this problem we need to create an isomorphic version of useLayoutEffect, which checks the environment in which this function is called the server or the client.

const useSafeLayoutEffect = canUseDOM()
  ? React.useLayoutEffect
  : React.useEffect;

To check in which environment we are, we can use this canUseDOM function:

const canUseDOM = () => {
  return !!(
    typeof window !== "undefined" &&
    window.document &&
    window.document.createElement
  );
};

Now we can use this new hook safely in server and client environments, the fallback to useEffect will be done automatically.

// The rules will be the same as useEffect/useLayoutEffect!
useSafeLayoutEffect(() => {
  console.log("I am safe now!");
}, []);

Conclusion

To solve this problem we need to create an isomorphic version of useLayoutEffect, which checks the environment in which this function is called the server or the client.

Get Access to Exclusive Content!

I'm going to produce some great stuff exclusively for front-end developers. I'll post new content including tips, tutorials and early access to future resources. Just subscribe and you’ll get my best posts delivered right to your inbox. I promise you won’t regret.