LogoLogo
  • Home
  • Services
    • Fiber
    • Accessor
    • Schema
    • Form
    • Translator
  • Components
    • <Router/>
    • <Memo />
  • Observables
    • Async
    • Value
    • Store
    • List
    • Local Storage Value
    • Local Storage Store
    • Local Storage List
  • Hooks
    • useAsync
    • useAffect
    • useStream
    • useAction
    • useDebounce
    • useThrottle
    • usePrevious
    • useIdle
    • useValue
    • useList
    • useStore
    • useForm
    • useFormBinder
    • useTranslator
    • useQuery
  • Helpers
    • Tag
    • Input Helpers
    • Promise Helpers
    • Save Helpers
    • Pagination Helpers
    • Clipboard Helpers
    • Calendar Helpers
    • Local Storage Helpers
Powered by GitBook
On this page

Was this helpful?

  1. Hooks

useAffect

React hook for async side effects

PrevioususeAsyncNextuseStream

Last updated 1 year ago

Was this helpful?

Source code is hosted on

yarn add @corets/use-affect
npm install --save @corets/use-async

This library is built on top of this package:

useAffect()

Takes a function or an instance of , 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 and documentation for more details and a comparison between those two hooks.

Async
useAsync
GitHub
Async
Async