# useAffect

Source code is hosted on [GitHub](https://github.com/corets/use-affect)

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

```sh
yarn add @corets/use-affect
```

{% endtab %}

{% tab title="npm" %}

```sh
npm install --save @corets/use-async
```

{% endtab %}
{% endtabs %}

This library is built on top of this package:

{% content-ref url="../observables/async" %}
[async](https://docs.corets.io/observables/async)
{% endcontent-ref %}

## useAffect()

Takes a function or an instance of [`Async`](https://docs.corets.io/observables/async#createasync), invokes it immediately, and keeps the state in sync with React. Function or Async instance may return an unsubscribe callback that is invoked before the component is unmounted.

This hook is especially useful when working with various subscription based data streams:

```typescript
import React, {useState} from "react"
import { createAsync } from "@corets/async"
import { useAsync } from "@corets/use-async"

const sharedValue = createAsync(async () => new Promise((resolve) => {
  const interval = setInterval(() => {
    console.log(new Date())    
  }, 1000)
  
  return () => clearInterval(interval)
))
    
const Example = () => {
  const [date, setDate] = useState<Date|null>()
  
  useAffect(async () => {
    return new Promise((resolve) => {
      const interval = setInterval(() => {
        setDate(new Date())
      }, 1000)
  
      return () => clearInterval(interval)
    )
  })
  
  return (
    <div>
      Current date is: {date?.toISOString()} 
    </div>
  )
}
```

{% hint style="info" %}
Check out [Async](https://docs.corets.io/observables/async) and [useAsync](https://docs.corets.io/hooks/use-async) documentation for more details and a comparison between those two hooks.
{% endhint %}
