React hook that recomputes a value every time one of its dependencies change -- also works with promises/async functions
yarn add use-computed-state
or if you use npm
npm install --save use-computed-state
import React, { useState } from 'react'
import useComputedState from 'use-computed-state'
const Example = () => {
let [items, setItems] = useState([])
let count = useComputedState(
() => items.length,
[items],
0
)
let promisedCount = useComputedState(
async () => {
let response = await Promise.resolve(items.length)
return response
},
[items],
0
)
return (
<div>
<button onClick={addItem}>add item</button>
<div>There are {count} items and {promisedCount} promised items</div>
</div>
)
function addItem(ev) {
ev.preventDefault()
setItems([...items, {name: 'new item'}])
}
}
Public Domain.