useAffect

React hook for async side effects

Source code is hosted on GitHub

yarn add @corets/use-affect

This library is built on top of this package:

useAffect()

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>
  )
}

Check out Async and useAsync documentation for more details and a comparison between those two hooks.

Last updated