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

use-conditional-effect

v1.0.1

Published

Replacement for React.useEffect with optional comparison function

Downloads

15

Readme

It's React's useEffect hook, except you can pass a comparison function.

Build Status Code Coverage version downloads MIT License

All Contributors PRs Welcome Code of Conduct

Watch on GitHub Star on GitHub Tweet

The problem

React's built-in useEffect hook has a second argument called the "dependencies array" and it allows you to decide when React will call your effect callback. React will do a comparison between each of the values (using Object.is, which is similar to ===) to determine whether your effect callback should be called.

The idea behind the dependencies array is that the identity of the items in the array will tell you when to run the effect.

There are several cases where object identity is not a good choice for triggering effects:

  • You want to call a callback function, which may change identity, when certain things change (not when the function itself changes). Sometimes you can memoize the function with useCallback, or assume someone else has done that, but doing so couples your effect condition to external code.
  • The values you need to compare require custom comparison (like a deep/recursive equality check).

Here's an example situation:

function Query({query, variables}) {
  // some code...

  // Who knows if this is a stable reference!
  const getQueryResult = useMyGraphQlLibrary()

  React.useEffect(
    () => {
      getQueryResult(query, variables)
    },
    // ⚠️ PROBLEMS!
    // - variables is a new object every render but we only want
    //   to run the effect when the username property changes
    // - getQueryResult might change but we don't want to run the
    //   effect when that happens
    [query, variables, getQueryResult],
  )

  return <div>{/* awesome UI here */}</div>
}

function QueryPageThing({username}) {
  const query = `
    query getUserData($username: String!) {
      user(login: $username) {
        name
      }
    }
  `
  const variables = {username}
  // poof! Every render `variables` will be a new object!
  return <Query query={query} variables={variables} />
}

Note

You could also solve the first problem if the QueryPageThing created the variables object like this: const variables = React.useMemo(() => ({username}), [username]). Then you wouldn't need this package. But sometimes you're writing a custom hook and you don't have control on what kinds of things people are passing you (or you want to give them a nice ergonomic API that can handle new objects every render).

In the second case, technically you don't have to add the callback to the dependencies array. But the exhaustive-deps ESLint rule automatically will add it unless you disable the rule.

This solution

This is a replacement for React.useEffect that accepts a comparison function in addition to the dependencies array. The comparison function gets the previous value of the dependencies as well as the current value, and the effect only runs if it returns true. Additionally, dependencies doesn't have to be an array, it can be an object or any other value.

Table of Contents

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save use-conditional-effect

Usage

You use it in place of React.useEffect.

Example:

import React from 'react'
import ReactDOM from 'react-dom'
import useConditionalEffect from 'use-conditional-effect'

function Query({query, variables}) {
  // Example: using some external library's method
  const getQueryResult = useMyGraphQlLibrary()

  // We don't need to use an array for the second argument
  // The third argument is the comparison function
  useConditionalEffect(
    () => {
      getQueryResult(query, variables)
    },
    {query, variables, getQueryResult},
    (current, previous = {}) => {
      if (
        current.query !== previous.query ||
        current.variables.username !== previous.variables.username
      ) {
        return true
      }
    },
  )

  return <div>{/* awesome UI here */}</div>
}

Compatibility with React.useEffect

  • If you don't pass the third argument, the comparison function defaults to the same comparison function as useEffect (thus, the second argument has to be an array in this case).
  • If you don't pass the second or third arguments, the effect always runs (same as useEffect).

Other Solutions

  • https://github.com/kentcdodds/use-deep-compare-effect

LICENSE

MIT