diff --git a/kotlin-react/src/main/kotlin/react/Imports.kt b/kotlin-react/src/main/kotlin/react/Imports.kt index 313d5b89e2b87..60e52b1180054 100644 --- a/kotlin-react/src/main/kotlin/react/Imports.kt +++ b/kotlin-react/src/main/kotlin/react/Imports.kt @@ -108,8 +108,13 @@ external interface ProfilerProps : RProps { external val Profiler: RClass // State Hook (16.8+) -@JsName("useState") -external fun rawUseState(initValue: T): RDependenciesArray +external fun useState( + initValue: T, +): RStateDelegate + +external fun useState( + valueInitializer: () -> T, +): RStateDelegate // Reducer Hook (16.8+) @JsName("useReducer") diff --git a/kotlin-react/src/main/kotlin/react/hooks.kt b/kotlin-react/src/main/kotlin/react/hooks.kt index 3b9798e9f96a9..f60a624d77d57 100644 --- a/kotlin-react/src/main/kotlin/react/hooks.kt +++ b/kotlin-react/src/main/kotlin/react/hooks.kt @@ -2,7 +2,6 @@ package react -import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty typealias RDependenciesArray = Array @@ -14,43 +13,24 @@ typealias RSetState = (value: T) -> Unit * Only works inside [functionalComponent] * @see https://reactjs.org/docs/hooks-state.html */ -inline fun useState(initValue: T): RStateDelegate { - val (state, setState) = rawUseState(initValue) - return RStateDelegate(state as T, setState as RSetState) -} +// TODO: make external in IR +class RStateDelegate +private constructor() { + inline operator fun component1(): T = asDynamic()[0] + inline operator fun component2(): RSetState = asDynamic()[1] -/** - * Only works inside [functionalComponent] - * @see https://reactjs.org/docs/hooks-state.html - */ -inline fun useState(noinline valueInitializer: () -> T): RStateDelegate { - val (state, setState) = rawUseState(valueInitializer) - return RStateDelegate(state as T, setState as RSetState) -} - -/** - * Only works inside [functionalComponent] - * @see https://reactjs.org/docs/hooks-state.html - */ -class RStateDelegate( - private val state: T, - private val setState: RSetState -) : ReadWriteProperty { - operator fun component1(): T = state - operator fun component2(): RSetState = setState - - override operator fun getValue( + inline operator fun getValue( thisRef: Nothing?, property: KProperty<*> ): T = - state + asDynamic()[0] - override operator fun setValue( + inline operator fun setValue( thisRef: Nothing?, property: KProperty<*>, value: T ) { - setState(value) + asDynamic()[1](value) } }