uam

use-async-memo

React hook for generating async memoized data.

Showing:

Popularity

Downloads/wk

1K

GitHub Stars

104

Maintenance

Last Commit

1mo ago

Contributors

4

Package

Dependencies

0

Size (min+gzip)

0.3KB

License

MIT

Type Definitions

Tree-Shakeable

No?

Categories

Readme

useAsyncMemo

React hook for generating async memoized data.

API

function useAsyncMemo<T>(factory: () => Promise<T>, deps: DependencyList, initial?: T): T

If factory returns undefined or null, useAsyncMemo will leave the memoized value unchanged.

Demo

Import

import {useAsyncMemo} from "use-async-memo"

Fetch API:

const data = useAsyncMemo(doAPIRequest, [])

or

const data = useAsyncMemo(() => doAPIRequest(), [])

or

const data = useAsyncMemo(() => {
  return doAPIRequest()
}, [])

or

const data = useAsyncMemo(async () => {
  return await doAPIRequest()
}, [])

Search on inputting:

const [input, setInput] = useState()
const users = useAsyncMemo(async () => {
  if (input === '') return []
  return await apiService.searchUsers(input)
}, [input], [])

Get loading status:

const [loading, setLoading] = useState(true)
const data = useAsyncMemo(async () => {
  setLoading(true)
  const response = await doAPIRequest()
  setLoading(false)
  return response
}, [])

With ability of manual clearing:

const [input, setInput] = useState()

const [clearFlag, setClearFlag] = useState({
  val: false
})
function clearItems() {
  setClearFlag({
    val: true
  })
}

const users = useAsyncMemo(async () => {
  if (clearFlag.val) {
    clearFlag.val = false
    return null
  }
  if (input === '') return []
  return await apiService.searchUsers(input)
}, [input, clearFlag], [])

With debounced value:

see use-debounce

const [input, setInput] = useState()
const [debouncedInput] = useDebounce(input, 300)
const users = useAsyncMemo(async () => {
  if (debouncedInput === '') return []
  return await apiService.searchUsers(debouncedInput)
}, [debouncedInput], [])

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
awmleerHangZhou, ZheJiang, China1 Rating0 Reviews
Coding is my way of life.
September 1, 2020