Skip to main content

flushSync

Check out the official React docs!

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


ReactDOM.flushSync forces React to apply the state updates inside the callback synchronously, so the DOM is already updated when flushSync returns. It returns the result of the callback.

Use it sparingly: it can hurt performance. Typical reasons are reading the layout right after an update (e.g. to scroll to a new element), or browser APIs that expect the DOM to change synchronously, like onbeforeprint.

ReactDOM.flushSync (fun () -> setItems (items @ [ newItem ]))
// The new item is in the DOM now.
listRef.current |> Option.iter (fun list -> list.scrollTop <- list.scrollHeight)
  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5
Show code
module Example.FlushSync

open Feliz

[<ReactComponent(true)>]
let FlushSync () =
let items, setItems = React.useState [ 1..5 ]
let listRef = React.useElementRef ()

Html.div [
Html.button [
prop.onClick (fun _ ->
ReactDOM.flushSync (fun () -> setItems (items @ [ items.Length + 1 ]))
// The new item is already in the DOM here, so scrolling reaches it.
listRef.current |> Option.iter (fun list -> list.scrollTop <- list.scrollHeight)
)
prop.text "Add item and scroll to it"
]
Html.ul [
prop.ref listRef
prop.style [ style.height 120; style.overflowY.auto ]
prop.children [ for item in items -> Html.li [ prop.key item; prop.text $"Item {item}" ] ]
]
]