npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cached-effect

v2.0.4

Published

React effect manager

Downloads

75

Readme

💥 React effect manager

NPM Version NPM Downloads GitHub issues Telegram

Manage effects in React using hooks. Create cached effects from async functions and handle them with useCache hook. Run your effects in order to update cache. It supports Concurrent Mode and rerenders components only when needed.

This package is very lightweight: 1.5kb minified (without react)

Installation

npm install cached-effect

or yarn

yarn add cached-effect

Usage

import { createEffect, useCache } from 'cached-effect'

Wrap a function that returns a promise in createEffect to create an effect:

const effect = createEffect(async () => { /* do something */ })

// or

const fetchUsers = createEffect(({ organizationId }) => axios
  .get(`/organizations/${organizationId}/users`)
  .then(getUsers)
)

Then use it in useCache hook in your React component:

const [users, usersError, usersLoading] = useCache(fetchUsers)

It returns an array of [result, error, pending]. These values stay the same until you run your effect. Use array destructuring to get values that you need.

Running effects

In order to update the cache you need to run your effect. For example, in useEffect hook inside of your component:

useEffect(() => {
  fetchUsers({ organizationId }) // or fetchUsers.once (see below)
}, [])

In this case users will be fetched after the component mounts. But it's useful to run your effect only once, for instance, when you have many mounting components using this effect:

useEffect(() => {
  fetchUsers.once({ organizationId })
}, [])

You can also refetch users or rerun any effect manually just calling it:

<Button
  type='button'
  onClick={() => fetchUsers({ organizationId })}
/>

React Hooks

useCache hook

Takes an effect and returns an array of [result, error, pending]:

const [result, error, pending] = useCache(effect)

It is equal to [undefined, null, false] by default and updates its values when you call the effect

usePending hook

Returns a pending status of your effect (true/false):

const pending = usePending(effect)

You can use it to show a spinner, for example. It is a syntactic sugar over useCache hook (the third value)

useError hook

Returns an error of your effect (or null):

const error = useError(effect)

You can use it if you need to show only an error of your effect somewhere. It is a syntactic sugar over useCache hook (the second value)

Effect

Effect is a container for an async function. It can be safely used in place of the original async function.

createEffect(handler)

Creates and returns an effect

effect(payload)

Runs an effect. Returns promise

effect.once(payload)

Runs an effect only once. Returns original promise on a repeated call

effect.watch(watcher)

Listens to the effect and calls watcher. Watcher receives payload and promise.

Returns back an unsubscribe function.

effect.use(handler)

Injects an async function into effect (can be called multiple times). This is useful for mocking API calls, testing etc.

effect.use.getCurrent()

Returns current effect handler

Promise

Promise is a container for async value. It has some additional methods.

promise.cache()

Returns a result synchronously if promise is completed successfully.

There will be no promise.cache method if promise is rejected!

promise.failure()

Returns an error synchronously if promise failed.

There will be no promise.failure method if promise fulfills!

promise.anyway()

Returns a promise that will be resolved anyway (aka .finally)

Tip

If you found this hook useful, please star this package on GitHub

Author

@doasync

Credits

This package was inspired by Effector library (from @ZeroBias). Effector is a reactive state manager, which has stores, events and effects as well as other useful features for managing state. This package is not compatible with effector effects right now.