useLazyRefState
All checks were successful
Lint / lint (push) Successful in 10s

This commit is contained in:
Julien Valverdé
2025-01-22 01:25:39 +01:00
parent 175cbaa704
commit 37cfcf6714
3 changed files with 29 additions and 1 deletions

View File

@@ -29,6 +29,7 @@
"clean:node": "rm -rf node_modules"
},
"devDependencies": {
"@typed/lazy-ref": "^0.3.3",
"@types/react": "^19.0.4",
"effect": "^3.12.1",
"react": "^19.0.0"

View File

@@ -1,3 +1,4 @@
import * as LazyRef from "@typed/lazy-ref"
import { Context, Effect, ExecutionStrategy, Exit, Fiber, Ref, Runtime, Scope, Stream, SubscriptionRef } from "effect"
import React from "react"
import * as ReffuseContext from "./ReffuseContext.js"
@@ -316,7 +317,7 @@ export class Reffuse<R> {
/**
* Binds the state of a `SubscriptionRef` to the state of the React component.
*
* Returns a [value, setter] tuple just like `React.useState` and triggers a re-render everytime the value of the ref changes.
* Returns a [value, setter] tuple just like `React.useState` and triggers a re-render everytime the value held by the ref changes.
*
* Note that the rules of React's immutable state still apply: updating a ref with the same value will not trigger a re-render.
*/
@@ -339,6 +340,32 @@ export class Reffuse<R> {
return [reactStateValue, setValue]
}
/**
* Binds the state of a `LazyRef` from the `@typed/lazy-ref` package to the state of the React component.
*
* Returns a [value, setter] tuple just like `React.useState` and triggers a re-render everytime the value held by the ref changes.
*
* Note that the rules of React's immutable state still apply: updating a ref with the same value will not trigger a re-render.
*/
useLazyRefState<A, E>(ref: LazyRef.LazyRef<A, E, R>): [A, React.Dispatch<React.SetStateAction<A>>] {
const runSync = this.useRunSync()
const initialState = React.useMemo(() => runSync(ref), [])
const [reactStateValue, setReactStateValue] = React.useState(initialState)
this.useFork(Stream.runForEach(ref.changes, v => Effect.sync(() =>
setReactStateValue(v)
)), [ref])
const setValue = React.useCallback((setStateAction: React.SetStateAction<A>) =>
runSync(LazyRef.update(ref, prevState =>
SetStateAction.value(setStateAction, prevState)
)),
[ref])
return [reactStateValue, setValue]
}
}