# Composing State

## Introduction

We advocate for creating atomic state and to compose new state when you need to.&#x20;

There are several composition operations that you can perform and that we will see below.

One key aspect of composing state is that it returns another ConanState, which you can compose again.

![Inception!](https://3967196510-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3BBQqsBUGjmzTvukhE%2F-MBiDaKel8uFQxR98PPz%2F-MBiEF6H4M2z1c9Hfa_v%2Finception.gif?alt=media\&token=0d154164-fc3c-4211-abb7-80fc7ba8fea6)

## One state to one state

### Map

We can derive one state into a new one using *ConanState*.*map*:

{% tabs %}
{% tab title="Js" %}

```javascript
productQty$.map((productQty)=>productQty.qty)

productPrice$.map((price)=>price.priceUsd)
```

{% endtab %}
{% endtabs %}

### Filter

We can filter 1 state into a new one using *ConanState.filter:*

```javascript
productQty$.filter((productQty) => productQty.qty % 2 === 0)
    
productQty$.filter((productQty)=>productQty.qty % 2 !== 0)
```

## Two states to one state

### Merge

We can merge 2 states into 1 using *ConanState.merge:*

{% tabs %}
{% tab title="Js" %}

```javascript
productQty$.merge(productPrice$, (productQty, productPrice)
 => productQty && productPrice ? productQty.qty * productPrice.priceUsd : 0)
```

{% endtab %}
{% endtabs %}

### Tuple

{% tabs %}
{% tab title="Js" %}

```javascript
productQty$.tuple(productPrice$)
```

{% endtab %}
{% endtabs %}

## **Many** states to one state

### **Combine**

We can combine N states into a new one using *ConanState.combine*:

{% tabs %}
{% tab title="Js" %}

```javascript
ConanState.combine(`combine`, {
    price: productPrice$,
    qty: productQty$
})
```

{% endtab %}

{% tab title="Ts" %}

```typescript
ConanState.combine<CombinedObject>(
    `combine`,
    {
        price: productPrice$,
        qty: productQty$
    }
)
```

{% endtab %}
{% endtabs %}

�

## Examples

You can navigate these examples in this sandbox:

{% embed url="<https://codesandbox.io/s/0po76?file=/src/app.tsx>" %}
Composing Conan states
{% endembed %}

## Composing State + Dependency Injection

Our dependency injection lets you describe atomic and composed state such that from the point of view of their consumers, they would not know (and won't care) wether if it is atomic state or not.

Check out our [dependency Injection](https://docs.conanjs.io/dependency-injection) for more details

## Demo

{% embed url="<https://codesandbox.io/s/3zs2m>" %}
