Skip to content

alexkrolick/use-conditional-effect

Repository files navigation

use-conditional-effect 🎲

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

LICENSE

MIT