Skip to main content

critical-timing-in-react

Learn about the critical timing in React. Understand the use of `useLayoutEffect` for immediate updates without visual inconsistencies.

––– views

useLayoutEffect in Zustand test-case explained size | Floating UI react-select MenuList

What is useLayoutEffect?

useLayoutEffect is similar to useEffect, but it fires synchronously after all DOM mutations and before the browser repaints the screen.

It ensures that updates inside this hook are reflected on the page immediately, without the user experiencing any visual inconsistency.

In contrast, useEffect runs after the browser repaints the screen, meaning the user might see the DOM in an interim state before the effect takes place.

When Should You Use useLayoutEffect?

You should use useLayoutEffect in situations where you need to ensure that the DOM has been updated before the browser paints the UI. Typical use cases include:

Measuring the DOM layout (e.g., for animations or measurements).

Synchronizing state or making changes that must be reflected in the DOM immediately.

Updating state that depends on DOM changes, such as adjusting styles or positions based on layout changes.

For less critical side effects, such as data fetching or logging, useEffect is generally preferred because it's non-blocking and doesn’t delay browser painting.

Handling state management when using Hooks

  1. Using a mutable ref to store state:

    In some scenarios, you might need to access the latest state value without resubscribing every time the state changes.

    You can achieve this by using useRef to create a mutable reference that stores the latest state value.

    This allows you to read from this reference anywhere in your component, bypassing the need for useState and useEffect re-rendering mechanisms.

  2. Implementing a more efficient subscription mechanism:

    If resubscribing upon state changes is necessary, consider designing an abstraction layer that makes resubscriptions low-cost and efficient.

    One approach is to defer the destruction of the connection (e.g., delaying the operation to the next tick), which allows you to freely resubscribe when the closed-over state changes.

How to read an often changing value from usecallback

React-select maxMenuHeight calculate example