Skip to main content

useInsertionEffect

Check out the official React docs!

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


useInsertionEffect is a version of useEffect that fires before React changes the DOM. It is meant for CSS-in-JS libraries that inject <style> tags, so the styles are in place before layout effects read the layout.

If you are not writing such a library, use useEffect or useLayoutEffect instead. You can't update state from an insertion effect, and refs aren't attached yet when it runs.

It has the same overloads as useLayoutEffect: the setup can return nothing, a cleanup function or an IDisposable.

React.useInsertionEffect (
(fun () ->
let styleElement = document.createElement "style"
styleElement.textContent <- css
document.head.appendChild styleElement |> ignore
fun () -> styleElement.remove ()),
[| box css |]
)
Styled by a rule inserted with useInsertionEffect.
Show code
module Example.UseInsertionEffect

open Browser
open Feliz

let private insertedRules = System.Collections.Generic.HashSet<string>()

/// A tiny CSS-in-JS helper: inserts a `<style>` rule once per class name, before any layout effect reads the DOM.
let useCss (className: string) (css: string) =
React.useInsertionEffect (
(fun () ->
if insertedRules.Add className then
let styleElement = document.createElement "style"
styleElement.textContent <- $".{className} {{ {css} }}"
document.head.appendChild styleElement |> ignore
),
[| box className; box css |]
)

className

[<ReactComponent(true)>]
let UseInsertionEffect () =
let className =
useCss "feliz-insertion-demo" "padding: 8px; border: 2px dashed rebeccapurple; border-radius: 6px;"

Html.div [
prop.className className
prop.text "Styled by a rule inserted with useInsertionEffect."
]