useEffectEvent
Check out the official React docs!
For more detailed information about React concepts and APIs, please refer to the official documentation for useEffectEvent.
note
Requires React 19.2 or later.
useEffectEvent wraps a function so that it always sees the latest props and state, while it can be left out of an effect's dependencies. Use it for logic that an effect triggers but that shouldn't restart the effect when it changes.
This is the clean fix for stale closures: an interval or a subscription created once still reads current values, without useRef or useStateWithUpdater workarounds.
let onTick = React.useEffectEvent (fun () -> setCount (fun count -> count + step))
React.useEffectOnce (fun () ->
let intervalId = JS.setInterval (fun () -> onTick ()) 1000
fun () -> JS.clearInterval intervalId)
In the example below, the interval is created once. Changing the step doesn't restart it, but the next tick uses the new step.
Count: 0
Show code
module Example.UseEffectEvent
open Fable.Core
open Feliz
[<ReactComponent(true)>]
let UseEffectEvent () =
let count, setCount = React.useStateWithUpdater 0
let step, setStep = React.useState 1
// Always reads the current `step`, but is not a dependency of the effect below.
let onTick = React.useEffectEvent (fun () -> setCount (fun count -> count + step))
// The interval is created once. Changing `step` doesn't restart it.
React.useEffectOnce (fun () ->
let intervalId = JS.setInterval (fun () -> onTick ()) 1000
fun () -> JS.clearInterval intervalId
)
Html.div [
Html.p $"Count: {count}"
Html.button [ prop.onClick (fun _ -> setStep (step + 1)); prop.text $"Step: {step} (click to increase)" ]
]
Rules
- Only call the returned function from inside effects (or from callbacks those effects set up), never during rendering.
- Don't pass it to other components or hooks.
- Don't add it to an effect's dependencies.