Comment on page
useAffect
React hook for async side effects
yarn
npm
yarn add @corets/use-affect
npm install --save @corets/use-async
This library is built on top of this package:
Takes a function or an instance of
Async
, 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:
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>
)
}
Last modified 6mo ago