use
For more detailed information about React concepts and APIs, please refer to the official documentation for use.
use reads the value of a promise or a context. In Feliz it is called React.use', because use is a keyword in F#.
Unlike other hooks, React.use' can be called inside if expressions and loops.
Reading a promise
React.use' suspends the component until the promise resolves. The nearest Suspense boundary shows its fallback in the meantime, and the nearest ErrorBoundary catches a rejected promise.
[<ReactComponent>]
let Quote (quotePromise: JS.Promise<string>) =
let quote = React.use' quotePromise
Html.p quote
React.Suspense([ Quote quotePromise ], Html.p "Loading quote...")
A promise created during render is a new promise on every render, so the component suspends forever. Create it in an event handler, in a parent component, in a router loader or a cache, and pass it down.
For the same reason there is no Async<'T> overload: converting an async to a promise during render would start a new request on every render.
No quote loaded yet.
Show code
module Example.Use
open Fable.Core
open Feliz
/// Pretends to fetch a quote from a server.
let fetchQuote (id: int) : JS.Promise<string> = promise {
do! Promise.sleep 1000
return $"Quote #{id}: Talk is cheap. Show me the code."
}
[<ReactComponent>]
let Quote (quotePromise: JS.Promise<string>) =
// Suspends until the promise resolves.
let quote = React.use' quotePromise
Html.p [ prop.style [ style.fontStyle.italic ]; prop.text quote ]
[<ReactComponent(true)>]
let Use () =
let nextId, setNextId = React.useState 1
// The promise is created in the click handler and stored in state, never during render.
let quotePromise, setQuotePromise = React.useState (None: JS.Promise<string> option)
Html.div [
Html.button [
prop.onClick (fun _ ->
setQuotePromise (Some(fetchQuote nextId))
setNextId (nextId + 1)
)
prop.text "Load a quote"
]
match quotePromise with
| Some quotePromise -> React.Suspense([ Quote quotePromise ], Html.p "Loading quote...")
| None -> Html.p "No quote loaded yet."
]
Reading a context
React.use' also reads a context, like useContext, but it may be called conditionally:
[<ReactComponent>]
let Heading (showTheme: bool) =
if showTheme then
let theme = React.use' ThemeContext
Html.h2 $"Theme: {theme}"
else
Html.h2 "Hello"