Skip to content

get values in react components that get recomputed whenever a dependency changes

License

Notifications You must be signed in to change notification settings

nbd-wtf/use-computed-state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

use-computed-state

React hook that recomputes a value every time one of its dependencies change -- also works with promises/async functions

NPM

Install

yarn add use-computed-state

or if you use npm

npm install --save use-computed-state

Usage

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

License

Public Domain.

About

get values in react components that get recomputed whenever a dependency changes

Resources

License

Stars

Watchers

Forks

Packages

No packages published