useReducer
Check out the official React docs!
For more detailed information about React concepts and APIs, please refer to the official documentation for useReducer.
useReducer
lets you manage complex state logic in your components using a reducer function, similar to Redux/Elmish.
This hook is useful for managing state transitions that depend on previous state, or when state logic is too complex for useState
.
The example is very simple and just demonstrates the basic usage of useReducer
.
type State = { Count : int }
type Msg = Increment | Decrement
let initialState = { Count = 0 }
let update (state: State) = function
| Increment -> { state with Count = state.Count + 1 }
| Decrement -> { state with Count = state.Count - 1 }
[<ReactComponent(true)>]
let UseReducer() =
let (state, dispatch) = React.useReducer(update, initialState)
Html.div [
Html.p [ prop.text $"Count: {state.Count}" ]
Html.button [
prop.text "+"
prop.onClick (fun _ -> dispatch Increment)
]
Html.button [
prop.text "-"
prop.onClick (fun _ -> dispatch Decrement)
]
Html.p [ prop.text "useReducer is useful for complex state logic." ]
]
Count: 0
useReducer is useful for complex state logic.
Show code
module Example.UseReducer
open Feliz
type State = { Count : int }
type Msg = Increment | Decrement
let initialState = { Count = 0 }
let update (state: State) (msg: Msg) =
match msg with
| Increment -> { state with Count = state.Count + 1 }
| Decrement -> { state with Count = state.Count - 1 }
[<ReactComponent(true)>]
let UseReducer() =
let (state, dispatch) = React.useReducer(update, initialState)
Html.div [
Html.p [ prop.text $"Count: {state.Count}" ]
Html.button [
prop.text "+"
prop.onClick (fun _ -> dispatch Increment)
]
Html.button [
prop.text "-"
prop.onClick (fun _ -> dispatch Decrement)
]
Html.p [ prop.text "useReducer is useful for complex state logic." ]
]