useLayoutEffect·续

export default function Tooltip({ children, targetRect }) { const ref = useRef(null); const [tooltipHeight, setTooltipHeight] = useState(0);

useLayoutEffect(() => { const { height } = ref.current.getBoundingClientRect(); setTooltipHeight(height); }, []);

let tooltipX = 0; let tooltipY = 0; if (targetRect !== null) { tooltipX = targetRect.left; tooltipY = targetRect.top - tooltipHeight; if (tooltipY < 0) { // It doesn't fit above, so place below. tooltipY = targetRect.bottom; } }

return createPortal( <TooltipContainer x={tooltipX} y={tooltipY} contentRef={ref}> {children} </TooltipContainer>, document.body ); }


```js src/TooltipContainer.js
export default function TooltipContainer({ children, x, y, contentRef }) {
  return (
    &lt;div
      style={{
        position: 'absolute',
        pointerEvents: 'none',
        left: 0,
        top: 0,
        transform: `translate3d(${x}px, ${y}px, 0)`
      }}
    >
      &lt;div ref={contentRef} className="tooltip">
        {children}
      &lt;/div>
    &lt;/div>
  );
}
.tooltip {
  color: white;
  background: #222;
  border-radius: 4px;
  padding: 4px;
}

useEffect does not block the browser

Here is the same example, but with useEffect instead of useLayoutEffect. If you're on a slower device, you might notice that sometimes the tooltip "flickers" and you briefly see its initial position before the corrected position.

import ButtonWithTooltip from './ButtonWithTooltip.js';

export default function App() {
  return (
    &lt;div>
      &lt;ButtonWithTooltip
        tooltipContent={
          &lt;div>
            This tooltip does not fit above the button.
            &lt;br />
            This is why it's displayed below instead!
          &lt;/div>
        }
      >
        Hover over me (tooltip above)
      &lt;/ButtonWithTooltip>
      &lt;div style={{ height: 50 }} />
      &lt;ButtonWithTooltip
        tooltipContent={
          &lt;div>This tooltip fits above the button&lt;/div>
        }
      >
        Hover over me (tooltip below)
      &lt;/ButtonWithTooltip>
      &lt;div style={{ height: 50 }} />
      &lt;ButtonWithTooltip
        tooltipContent={
          &lt;div>This tooltip fits above the button&lt;/div>
        }
      >
        Hover over me (tooltip below)
      &lt;/ButtonWithTooltip>
    &lt;/div>
  );
}

```js src/ButtonWithTooltip.js import { useState, useRef } from 'react'; import Tooltip from './Tooltip.js';

export default function ButtonWithTooltip({ tooltipContent, ...rest }) { const [targetRect, setTargetRect] = useState(null); const buttonRef = useRef(null); return ( <> <button {...rest} ref={buttonRef} onPointerEnter={() => { const rect = buttonRef.current.getBoundingClientRect(); setTargetRect({ left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom, }); }} onPointerLeave={() => { setTargetRect(null); }} /> {targetRect !== null && ( <Tooltip targetRect={targetRect}> {tooltipContent} </Tooltip> ) } </> ); }


```js src/Tooltip.js active
import { useRef, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import TooltipContainer from './TooltipContainer.js';

export default function Tooltip({ children, targetRect }) {
  const ref = useRef(null);
  const [tooltipHeight, setTooltipHeight] = useState(0);

useEffect(() => {
    const { height } = ref.current.getBoundingClientRect();
    setTooltipHeight(height);
  }, []);

let tooltipX = 0;
  let tooltipY = 0;
  if (targetRect !== null) {
    tooltipX = targetRect.left;
    tooltipY = targetRect.top - tooltipHeight;
    if (tooltipY < 0) {
      // It doesn't fit above, so place below.
      tooltipY = targetRect.bottom;
    }
  }

return createPortal(
    &lt;TooltipContainer x={tooltipX} y={tooltipY} contentRef={ref}>
      {children}
    &lt;/TooltipContainer>,
    document.body
  );
}

``js src/TooltipContainer.js export default function TooltipContainer({ children, x, y, contentRef }) { return ( &lt;div style={{ position: 'absolute', pointerEvents: 'none', left: 0, top: 0, transform:translate3d(${x}px, ${y}px, 0)` }} > <div ref={contentRef} className="tooltip"> {children} </div> </div> ); }


```css
.tooltip {
  color: white;
  background: #222;
  border-radius: 4px;
  padding: 4px;
}

To make the bug easier to reproduce, this version adds an artificial delay during rendering. React will let the browser paint the screen before it processes the state update inside useEffect. As a result, the tooltip flickers:

import ButtonWithTooltip from './ButtonWithTooltip.js';

export default function App() {
  return (
    &lt;div>
      &lt;ButtonWithTooltip
        tooltipContent={
          &lt;div>
            This tooltip does not fit above the button.
            &lt;br />
            This is why it's displayed below instead!
          &lt;/div>
        }
      >
        Hover over me (tooltip above)
      &lt;/ButtonWithTooltip>
      &lt;div style={{ height: 50 }} />
      &lt;ButtonWithTooltip
        tooltipContent={
          &lt;div>This tooltip fits above the button&lt;/div>
        }
      >
        Hover over me (tooltip below)
      &lt;/ButtonWithTooltip>
      &lt;div style={{ height: 50 }} />
      &lt;ButtonWithTooltip
        tooltipContent={
          &lt;div>This tooltip fits above the button&lt;/div>
        }
      >
        Hover over me (tooltip below)
      &lt;/ButtonWithTooltip>
    &lt;/div>
  );
}

```js src/ButtonWithTooltip.js import { useState, useRef } from 'react'; import Tooltip from './Tooltip.js';

export default function ButtonWithTooltip({ tooltipContent, ...rest }) { const [targetRect, setTargetRect] = useState(null); const buttonRef = useRef(null); return ( <> <button {...rest} ref={buttonRef} onPointerEnter={() => { const rect = buttonRef.current.getBoundingClientRect(); setTargetRect({ left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom, }); }} onPointerLeave={() => { setTargetRect(null); }} /> {targetRect !== null && ( <Tooltip targetRect={targetRect}> {tooltipContent} </Tooltip> ) } </> ); }


```js {expectedErrors: {'react-compiler': [10, 11]}} src/Tooltip.js active
import { useRef, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import TooltipContainer from './TooltipContainer.js';

export default function Tooltip({ children, targetRect }) {
  const ref = useRef(null);
  const [tooltipHeight, setTooltipHeight] = useState(0);

// This artificially slows down rendering
  let now = performance.now();
  while (performance.now() - now < 100) {
    // Do nothing for a bit...
  }

useEffect(() => {
    const { height } = ref.current.getBoundingClientRect();
    setTooltipHeight(height);
  }, []);

let tooltipX = 0;
  let tooltipY = 0;
  if (targetRect !== null) {
    tooltipX = targetRect.left;
    tooltipY = targetRect.top - tooltipHeight;
    if (tooltipY < 0) {
      // It doesn't fit above, so place below.
      tooltipY = targetRect.bottom;
    }
  }

return createPortal(
    &lt;TooltipContainer x={tooltipX} y={tooltipY} contentRef={ref}>
      {children}
    &lt;/TooltipContainer>,
    document.body
  );
}

``js src/TooltipContainer.js export default function TooltipContainer({ children, x, y, contentRef }) { return ( &lt;div style={{ position: 'absolute', pointerEvents: 'none', left: 0, top: 0, transform:translate3d(${x}px, ${y}px, 0)` }} > <div ref={contentRef} className="tooltip"> {children} </div> </div> ); }


```css
.tooltip {
  color: white;
  background: #222;
  border-radius: 4px;
  padding: 4px;
}

Edit this example to useLayoutEffect and observe that it blocks the paint even if rendering is slowed down.

[!NOTE]

Rendering in two passes and blocking the browser hurts performance. Try to avoid this when you can.


Troubleshooting

I'm getting an error: "useLayoutEffect does nothing on the server"

The purpose of useLayoutEffect is to let your component use layout information for rendering:

  1. Render the initial content.
  2. Measure the layout before the browser repaints the screen.
  3. Render the final content using the layout information you've read.

When you or your framework uses server rendering, your React app renders to HTML on the server for the initial render. This lets you show the initial HTML before the JavaScript code loads.

The problem is that on the server, there is no layout information.

In the earlier example, the useLayoutEffect call in the Tooltip component lets it position itself correctly (either above or below content) depending on the content height. If you tried to render Tooltip as a part of the initial server HTML, this would be impossible to determine. On the server, there is no layout yet! So, even if you rendered it on the server, its position would "jump" on the client after the JavaScript loads and runs.

Usually, components that rely on layout information don't need to render on the server anyway. For example, it probably doesn't make sense to show a Tooltip during the initial render. It is triggered by a client interaction.

However, if you're running into this problem, you have a few different options:

  • Replace useLayoutEffect with useEffect. This tells React that it's okay to display the initial render result without blocking the paint (because the original HTML will become visible before your Effect runs).

  • Alternatively, call use(browser()) to mark the component as browser-only. React will replace its content up to the closest <Suspense> boundary with a loading fallback (for example, a spinner or a glimmer) during server rendering.

  • Alternatively, mark your component as client-only. This tells React to replace its content up to the closest <Suspense> boundary with a loading fallback during server rendering.

  • Alternatively, you can render a component with useLayoutEffect only after hydration. Keep a boolean isMounted state that's initialized to false, and set it to true inside a useEffect call. Your rendering logic can then be like return isMounted ? <RealContent /> : <FallbackContent />. On the server and during the hydration, the user will see FallbackContent which should not call useLayoutEffect. Then React will replace it with RealContent which runs on the client only and can include useLayoutEffect calls.

  • If you synchronize your component with an external data store and rely on useLayoutEffect for different reasons than measuring layout, consider useSyncExternalStore instead which supports server rendering.


Sitemap

Overview of all docs pages