@ -1751,6 +1751,8 @@ function ChatRoom({ roomId }) {
* If your Effect wasn't caused by an interaction (like a click), React will let the browser **paint the updated screen first before running your Effect.** If your Effect is doing something visual (for example, positioning a tooltip), and the delay is noticeable (for example, it flickers), you need to replace `useEffect` with [`useLayoutEffect`.](/apis/react/useLayoutEffect)
* Even if your Effect was caused by an interaction (like a click), **the browser may repaint the screen before processing the state updates inside your Effect.** Usually, that's what you want. However, if you must block the browser from repainting the screen, you need to replace `useEffect` with [`useLayoutEffect`.](/apis/react/useLayoutEffect)
* Effects **only run on the client.** They don't run during server rendering.
This section is incomplete, please see the old docs for [useLayoutEffect.](https://reactjs.org/docs/hooks-reference.html#uselayouteffect)
</Wip>
`useLayoutEffect` can hurt performance. Prefer [`useEffect`](/apis/react/useEffect) when possible.
</Pitfall>
<Intro>
`useLayoutEffect` is a version of [`useEffect`](/apis/react/useEffect) that fires before any DOM mutations.
```js
useLayoutEffect(callback, [...dependencies])
useLayoutEffect(setup, dependencies?)
```
</Intro>
<InlineToc/>
---
## Usage {/*usage*/}
### Measuring layout before the browser repaints the screen {/*measuring-layout-before-the-browser-repaints-the-screen*/}
Most components don't need to know their position and size on the screen to decide what to render. They only return some JSX with CSS. Then the browser calculates their *layout* (position and size) and repaints the screen.
Sometimes, that's not enough. Imagine a tooltip that appears next to some element on hover. If there's enough space, the tooltip should appear above the element, but if it doesn't fit, it should appear below. This means that in order to render the tooltip at the right final position, you need to know its height (i.e. whether it fits at the top).
To do this, you need to render in two passes:
1. Render the tooltip anywhere (even with a wrong position).
2. Measure its height and decide where to place the tooltip.
3. Render the tooltip *again* in the correct place.
**All of this needs to happen before the browser repaints the screen.** You don't want the user to see the tooltip moving. Call `useLayoutEffect` to perform the layout measurements before the browser repaints the screen:
```js {5-8}
function Tooltip() {
const ref = useRef(null);
const [tooltipHeight, setTooltipHeight] = useState(0); // You don't know real height yet
setTooltipHeight(height); // Re-render now that you know the real height
}, []);
// ...use tooltipHeight in the rendering logic below...
}
```
Here's how this works step by step:
1. `Tooltip` renders with the initial `tooltipHeight = 0` (so the tooltip may be wrongly positioned).
2. React places it in the DOM and runs the code in `useLayoutEffect`.
3. Your `useLayoutEffect` [measures the height](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of the tooltip content and triggers an immediate re-render.
4. `Tooltip` renders again with the real `tooltipHeight` (so the tooltip is correctly positioned).
5. React updates it in the DOM, and the browser finally displays the tooltip.
Hover over the buttons below and see how the tooltip adjusts its position depending on whether it fits:
<Sandpack>
```js
import ButtonWithTooltip from './ButtonWithTooltip.js';
export default function App() {
return (
<div>
<ButtonWithTooltip
tooltipContent={
<div>
This tooltip does not fit above the button.
<br/>
This is why it's displayed below instead!
</div>
}
>
Hover over me (tooltip above)
</ButtonWithTooltip>
<divstyle={{height:50}}/>
<ButtonWithTooltip
tooltipContent={
<div>This tooltip fits above the button</div>
}
>
Hover over me (tooltip below)
</ButtonWithTooltip>
<divstyle={{height:50}}/>
<ButtonWithTooltip
tooltipContent={
<div>This tooltip fits above the button</div>
}
>
Hover over me (tooltip below)
</ButtonWithTooltip>
</div>
);
}
```
```js ButtonWithTooltip.js
import { useState, useRef } from 'react';
import Tooltip from './Tooltip.js';
export default function ButtonWithTooltip({ tooltipContent, ...rest }) {
export default function TooltipContainer({ children, x, y, contentRef }) {
return (
<div
style={{
position: 'absolute',
pointerEvents: 'none',
left: 0,
top: 0,
transform: `translate3d(${x}px, ${y}px, 0)`
}}
>
<divref={contentRef}className="tooltip">
{children}
</div>
</div>
);
}
```
```css
.tooltip {
color: white;
background: #222;
border-radius: 4px;
padding: 4px;
}
```
</Sandpack>
Notice that even though the `Tooltip` component has to render in two passes (first, with `tooltipHeight` initialized to `0` and then with the real measured height), you only see the final result. This is why you need `useLayoutEffect` instead of [`useEffect`](/apis/react/useEffect) for this example. Let's look at the difference in detail below.
<RecipestitleText="useLayoutEffect vs useEffect"titleId="examples">
#### `useLayoutEffect` blocks the browser from repainting {/*uselayouteffect-blocks-the-browser-from-repainting*/}
React guarantees that the code inside `useLayoutEffect` and any state updates scheduled inside it will be processed **before the browser repaints the screen.** This lets you render the tooltip, measure it, and re-render the tooltip again without the user noticing the first extra render. In other words, `useLayoutEffect` blocks the browser from painting.
<Sandpack>
```js
import ButtonWithTooltip from './ButtonWithTooltip.js';
export default function App() {
return (
<div>
<ButtonWithTooltip
tooltipContent={
<div>
This tooltip does not fit above the button.
<br/>
This is why it's displayed below instead!
</div>
}
>
Hover over me (tooltip above)
</ButtonWithTooltip>
<divstyle={{height:50}}/>
<ButtonWithTooltip
tooltipContent={
<div>This tooltip fits above the button</div>
}
>
Hover over me (tooltip below)
</ButtonWithTooltip>
<divstyle={{height:50}}/>
<ButtonWithTooltip
tooltipContent={
<div>This tooltip fits above the button</div>
}
>
Hover over me (tooltip below)
</ButtonWithTooltip>
</div>
);
}
```
```js ButtonWithTooltip.js
import { useState, useRef } from 'react';
import Tooltip from './Tooltip.js';
export default function ButtonWithTooltip({ tooltipContent, ...rest }) {
export default function TooltipContainer({ children, x, y, contentRef }) {
return (
<div
style={{
position: 'absolute',
pointerEvents: 'none',
left: 0,
top: 0,
transform: `translate3d(${x}px, ${y}px, 0)`
}}
>
<divref={contentRef}className="tooltip">
{children}
</div>
</div>
);
}
```
```css
.tooltip {
color: white;
background: #222;
border-radius: 4px;
padding: 4px;
}
```
</Sandpack>
<Solution/>
#### `useEffect` does not block the browser {/*useeffect-does-not-block-the-browser*/}
Here is the same example, but with [`useEffect`](/apis/react/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.
<Sandpack>
```js
import ButtonWithTooltip from './ButtonWithTooltip.js';
export default function App() {
return (
<div>
<ButtonWithTooltip
tooltipContent={
<div>
This tooltip does not fit above the button.
<br/>
This is why it's displayed below instead!
</div>
}
>
Hover over me (tooltip above)
</ButtonWithTooltip>
<divstyle={{height:50}}/>
<ButtonWithTooltip
tooltipContent={
<div>This tooltip fits above the button</div>
}
>
Hover over me (tooltip below)
</ButtonWithTooltip>
<divstyle={{height:50}}/>
<ButtonWithTooltip
tooltipContent={
<div>This tooltip fits above the button</div>
}
>
Hover over me (tooltip below)
</ButtonWithTooltip>
</div>
);
}
```
```js ButtonWithTooltip.js
import { useState, useRef } from 'react';
import Tooltip from './Tooltip.js';
export default function ButtonWithTooltip({ tooltipContent, ...rest }) {
export default function TooltipContainer({ children, x, y, contentRef }) {
return (
<div
style={{
position: 'absolute',
pointerEvents: 'none',
left: 0,
top: 0,
transform: `translate3d(${x}px, ${y}px, 0)`
}}
>
<divref={contentRef}className="tooltip">
{children}
</div>
</div>
);
}
```
```css
.tooltip {
color: white;
background: #222;
border-radius: 4px;
padding: 4px;
}
```
</Sandpack>
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:
<Sandpack>
```js
import ButtonWithTooltip from './ButtonWithTooltip.js';
export default function App() {
return (
<div>
<ButtonWithTooltip
tooltipContent={
<div>
This tooltip does not fit above the button.
<br/>
This is why it's displayed below instead!
</div>
}
>
Hover over me (tooltip above)
</ButtonWithTooltip>
<divstyle={{height:50}}/>
<ButtonWithTooltip
tooltipContent={
<div>This tooltip fits above the button</div>
}
>
Hover over me (tooltip below)
</ButtonWithTooltip>
<divstyle={{height:50}}/>
<ButtonWithTooltip
tooltipContent={
<div>This tooltip fits above the button</div>
}
>
Hover over me (tooltip below)
</ButtonWithTooltip>
</div>
);
}
```
```js ButtonWithTooltip.js
import { useState, useRef } from 'react';
import Tooltip from './Tooltip.js';
export default function ButtonWithTooltip({ tooltipContent, ...rest }) {
* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. Before your component is first added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. Before your component is removed from the DOM, React will run your cleanup function one last time.
* **optional**`dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don't specify the dependencies at all, your Effect will re-run after every re-render of the component.
#### Returns {/*returns*/}
`useLayoutEffect` returns `undefined`.
#### Caveats {/*caveats*/}
* `useEffect` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic "mirrors" your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, [you need to implement the cleanup function.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
* If some of your dependencies are objects or functions defined inside the component, there is a risk that they will **cause the Effect to re-run more often than needed.** To fix this, remove unnecessary [object](/apis/react/useEffect#removing-unnecessary-object-dependencies) and [function](/apis/react/useEffect#removing-unnecessary-function-dependencies) dependencies. You can also [extract state updates](/apis/react/useEffect#updating-state-based-on-previous-state-from-an-effect) and [non-reactive logic](/apis/react/useEffect#reading-the-latest-props-and-state-from-an-effect) outside of your Effect.
* Effects **only run on the client.** They don't run during server rendering.
* The code inside `useLayoutEffect` and all state updates scheduled from it **block the browser from repainting the screen.** When used excessively, this can make your app very slow. When possible, prefer [`useEffect`.](/apis/reac/useEffect)
---
## Troubleshooting {/*troubleshooting*/}
### I'm getting an error: "`useLayoutEffect` does nothing on the server" {/*im-getting-an-error-uselayouteffect-does-nothing-on-the-server*/}
The purpose of `useLayoutEffect` is to let your component [use layout information for rendering:](#measuring-layout-before-the-browser-repaints-the-screen)
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](/apis/react-dom/server), 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](#measuring-layout-before-the-browser-repaints-the-screen), 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 browser and no layout! 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 options:
1. You can replace `useLayoutEffect` with [`useEffect`.](/apis/react/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).
2. You can [mark your component as client-only.](/apis/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content) This tells React to replace its content up to the closest [`<Suspense>`](/apis/react/Suspense) boundary with a loading fallback (for example, a spinner or a glimmer) during server rendering.
3. You can display different components on the server and on the client. One way to do this is to 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.
4. If you synchronize your component with an external data store and rely on `useLayoutEffect` for different reasons than measuring layout, consider [`useSyncExternalStore`](/apis/react/useSyncExternalStore) instead which [supports server rendering.](/apis/react/useSyncExternalStore#adding-support-for-server-rendering)