useFacetLayoutEffect
Much like React offers a useLayoutEffect as a complement to useEffect, so too does react-facet offer a useFacetLayoutEffect. It takes the exact same input as useFacetEffect and has an identical implementation, the sole exception being that it uses React's underlying useLayoutEffect instead that fires synchronously after all DOM mutations.
When to Use
Use useFacetLayoutEffect when you need to:
- Measure DOM elements before the browser paints
- Make synchronous DOM mutations
- Read layout from the DOM and synchronously re-render
Example
tsximport {useFacetLayoutEffect ,useFacetState ,Facet } from '@react-facet/core'import {useRef } from 'react'constMeasureElement = ({dimensionsFacet }: {dimensionsFacet :Facet <{width : number;height : number }> }) => {constelementRef =useRef <HTMLDivElement >(null)useFacetLayoutEffect ((dimensions ) => {// Synchronously measure the element after dimensions changeif (elementRef .current ) {constrect =elementRef .current .getBoundingClientRect ()console .log ('Element measured:',rect .width , 'x',rect .height )}},[],[dimensionsFacet ],)return <div ref ={elementRef }>Measured content</div >}
Comparison with useFacetEffect
| Feature | useFacetEffect | useFacetLayoutEffect |
|---|---|---|
| Execution timing | Asynchronous | Synchronous |
| Browser paint | After paint | Before paint |
| Use case | Data fetching, logging | DOM measurements, mutations |
| Performance impact | Lower | Can block visual updates |
Performance Warning
useFacetLayoutEffect runs synchronously, which can block the browser from painting. Use useFacetEffect unless you specifically need synchronous DOM operations.