Skip to main content

useState

Check out the official React docs!

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


useState is a hook that lets you store and update variables for your components. Changes in react states trigger a re-render of the component.


[<ReactComponent>]
let MyComponent() =
let count, setCount = React.useState(42)
let result, setResult = React.useState(None: int option)

// ...

0

Show code
module Example.Counter

open Fable.Core
open Feliz

[<Erase; Mangle(false)>]
type Counter =

[<ReactComponent(true)>]
static member Counter() =

let (count, setCount) = React.useState 0

Html.div [
Html.h1 count
Html.button [
prop.text "Increment"
prop.onClick (fun _ -> setCount(count + 1))
]
]

useStateWithUpdater

useStateWithUpdater is a Feliz specific variant of useState that allows you to update the state based on its previous value. In javascript React the setter function is overloaded to accept either a value or an updater function. In F# this is not possible due to the strong typing, so Feliz provides this additional hook.

This is useful when dealing with async information. Such as debounced input or data from remote APIs.

Show code
module Example.UseStateWithUpdater

open Feliz

[<ReactComponent(true)>]
let UseStateWithUpdater() =
let results, setResults = React.useStateWithUpdater([]: string list)

let asyncAddResult (text: string) (sleep: int) =
async {
do! Async.Sleep sleep
// Use the updater function to append to the list
setResults (fun current -> current @ [ text ])
} |> Async.StartImmediate

Html.div [
if results.IsEmpty then
Html.button [
prop.text "Run"
prop.onClick (fun _ ->
// Simulate async work
asyncAddResult "First" 1000
asyncAddResult "Second" 500
asyncAddResult "Third" 1500
asyncAddResult "Fourth" 2000
)
]
else
for i in 0 .. results.Length - 1 do
Html.div [
prop.key i
prop.text results.[i]
]
]