# \[Tool\] Kotin React Prop and State Delegates

**URL:** <https://discuss.kotlinlang.org/t/tool-kotin-react-prop-and-state-delegates/16157>\
**Category:** JavaScript\
**Created:** [January 31, 2020, 10:50am UTC](https://discuss.kotlinlang.org/t/tool-kotin-react-prop-and-state-delegates/16157 "2020-01-31T10:50:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jolanrensen](https://avatars.discourse-cdn.com/v4/letter/j/ba8739/32.png) [@Jolanrensen](https://discuss.kotlinlang.org/u/Jolanrensen)\
**Post date:** [January 31, 2020, 10:50am UTC](https://discuss.kotlinlang.org/t/tool-kotin-react-prop-and-state-delegates/16157/1 "2020-01-31T10:50:57Z")

</div>

Hi everyone,  
While working on a React Kotlin/JS project I felt the need to not have to type `setState{ }` and `props.item` everytime I needed a variable from the props or state. I also didn’t feel like creating two props for just one item because a child needed a getter and a setter function. After a lot a trying I created StateDelegate, StateAsProp, ReadWritePropDelegate and ReadOnlyDelegate classes with their own creation functions. Together, I call them [React Prop and State Delegates](https://github.com/Jolanrensen/Kotlin-React-Prop-and-State-Delegates).  
I know not everyone will like having to type even more in small components, but in larger ones it might help.

Using a delegated state inside a component

```
setState {
    counter = state.counter + 1
}

```

becomes

```
counter++

```

Even better:

```
setState {
    yourSet = state.yourSet + item
}

```

becomes

```
yourSet += item

```

All you need to do is declare the delegates somewhere in your component like:

```
var counter by stateDelegateOf(YourState::counter)

```

If you need to give a childComponent read/write access to an item in your state, normally you’d need to give it a getter and setter prop, so a child might have to call:

```
props.setItem(props.item + something)

```

Well, by passing a `StateAsProp` to a child, the child can simply

```
var item by propDelegateOf(ChildProps::item)

fun someFunction() {
    item += something
}

```

Normal props can also be made read-only and accessible without `props.x` by using the same command:

```
val otherItem by propDelegateOf(ChildProps::otherItem)

```

Anyways, if you’d like to check it out, it’s over at: [https://github.com/Jolanrensen/Kotlin-React-Prop-and-State-Delegates](https://github.com/Jolanrensen/Kotlin-React-Prop-and-State-Delegates) .  
I don’t know how to create a library yet, but for now you can just copy over the file if you like to use it yourself.
