Skip to main content
useLayoutEffect is a drop-in replacement for React’s useLayoutEffect that suppresses the warning emitted during server-side rendering by replacing the hook with a no-op function in non-browser environments.

Installation

Function Signature

Why Use This?

React’s useLayoutEffect emits a warning on the server because neither useLayoutEffect nor useEffect run during server-side rendering. This safe version suppresses the warning by using a no-op function when document is not available (i.e., in SSR environments).

Usage

Basic Example

Measuring DOM Elements

Updating Refs Before Paint

Implementation

The implementation is straightforward:
  • If document exists (browser environment), use React’s useLayoutEffect
  • Otherwise (SSR environment), use a no-op function

When to Use

Use useLayoutEffect when you need to:
  • Measure DOM elements before the browser paints
  • Make DOM mutations that need to be visible immediately
  • Read layout from the DOM and synchronously re-render
  • Avoid visual flashing that would occur with useEffect

Notes

This hook follows the same API as React’s useLayoutEffect. The only difference is that it doesn’t emit warnings during server-side rendering.
In SSR environments, the hook becomes a no-op (doesn’t run at all). If you need your effect to run on the server, use useEffect instead, though keep in mind that useEffect also doesn’t run on the server.
For more information about useLayoutEffect, see the React documentation.