diff --git a/kotlin-react/src/main/kotlin/react/hooks.kt b/kotlin-react/src/main/kotlin/react/hooks.kt index 18a7f18543916..8db2a987044a4 100644 --- a/kotlin-react/src/main/kotlin/react/hooks.kt +++ b/kotlin-react/src/main/kotlin/react/hooks.kt @@ -1,5 +1,8 @@ package react +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty + typealias RDependenciesArray = Array typealias RDependenciesList = List @@ -19,6 +22,25 @@ fun useState(valueInitializer: () -> T): Pair> { return currentValue to setState } +private class ReactStateDelegate(useState: Pair>) : ReadWriteProperty { + private val state = useState.first + + private val setState = useState.second + + override operator fun getValue(thisRef: Any?, property: KProperty<*>): T = + state + + override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { + setState(value) + } +} + +fun state(initValue: T): ReadWriteProperty = + ReactStateDelegate(useState(initValue)) + +fun state(valueInitializer: () -> T): ReadWriteProperty = + ReactStateDelegate(useState(valueInitializer)) + typealias RReducer = (state: S, action: A) -> S typealias RDispatch = (action: A) -> Unit