Article thumbnail

🔰 Removing server warnings for useLayoutEffect with custom hook

3m
frontend
ui
hooks

Intro

Crafting a concise hook to eliminate intimidating warnings in Next.js or Gatsby, addressing the root cause and understanding its occurrence.

Why you see this long and weird error?

This article will be linked in other articles many times - this hook is used really often when writing SSR working hooks/components.

"The 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."

Why you see this error? The useLayoutEffect is designed for reading real DOM information from the browser environment (client-side). On server side, there is no DOM, so when we'll try to create our hooks/components and we'll use useLayoutEffect on the server, the initial expected result may be weird - aka buggy as hell. That's why frameworks skip calling this hook.

In other frameworks like Gatsby the similar approach is used.

The useEffect calls are also skipped on server-side. This hook is designed for client-side code, but that's not a part of this article.

In following Github thread you may find more information.

Fixing this weird warning

You need to do following stuff to fix it:

  • check is the code executed in the server environment,
  • if it's a server environment, you need to call empty function instead of useLayoutEffect,

or you may

  • lazy load the component.

Loading

Now we need to use our hook in components or custom hooks.

Loading

I showed you two of the most popular names/implementations for this hook. What is important, you may avoid using this when you're sure that your code is executed only on the client-side. For example, it may happen when you use the code splitting/lazy loading technique.

Loading

Conclusions

Now we know how to fix this weird warning and we know that useLayoutEffect and useEffect calls are skipped on the server side in all SSR/SSG frameworks. It happens because there is no option to access browser DOM object on the server side.

In addition, we know that for useLayoutEffect there is a warning prompted during build phase or when a component will be dynamically rendered with SSG technique. So, when it will happen - just use our newly created, simple abstractions.

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.

Comments

Add your honest opinion about this article and help us improve the content.

created: 20-03-2023
updated: 20-03-2023