Skip to main content

useLayoutEffect

Check out the official React docs!

For more detailed information about React concepts and APIs, please refer to the official documentation for useLayoutEffect.


useLayoutEffect runs synchronously after all DOM mutations, before the browser paints. It's useful for reading layout and synchronously re-rendering.

[<ReactComponent(true)>]
let UseLayoutEffect() =
React.useLayoutEffect((fun () ->
JS.console.log($"layout effect!")
fun () -> JS.console.log("Cleanup layout effect")
),
[|
// .. dependencies
|]
)
This is a tooltip.

Measured tooltip height: 0px

Show code
module Example.UseLayoutEffect

open Feliz


[<ReactComponent(true)>]
let Tooltip() =
let tooltipRef = React.useElementRef()
let tooltipHeight, setTooltipHeight = React.useState(0)
let padding, setPadding = React.useState(10)

React.useLayoutEffect((fun () ->
match tooltipRef.current with
| Some el ->
let rect = el.getBoundingClientRect()
setTooltipHeight(int rect.height)
| None -> ()
), [| box padding |])

Html.div [
Html.div [
prop.ref tooltipRef
prop.style [ style.backgroundColor.lightYellow; style.color.black; style.padding padding ]
prop.text "This is a tooltip."
]
Html.p [ prop.text $"Measured tooltip height: {tooltipHeight}px" ]
Html.input [
prop.type'.number
prop.value padding
prop.onChange setPadding
prop.placeholder "Set tooltip padding"
]
]

useLayoutEffectOnce

useLayoutEffectOnce is a Feliz helper that runs a layout effect only once after the initial render.

See example above.