# 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="/pages/-Mg7Kt8XOfsD4Np5cHGW" %}
[Async](/observables/async.md)
{% endcontent-ref %}

## useAffect()

Takes a function or an instance of [`Async`](/observables/async.md#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](/observables/async.md) and [useAsync](/hooks/use-async.md) documentation for more details and a comparison between those two hooks.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.corets.io/hooks/useaffect.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
