All Projects → alexkrolick → Use Conditional Effect

alexkrolick / Use Conditional Effect

Licence: mit
React.useEffect, except you can pass a comparison function.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Use Conditional Effect

Dahlia
An opinionated React Framework. [Rename to pea.js]
Stars: ✭ 92 (-17.12%)
Mutual labels:  hooks
React Gesture Responder
a gesture responder system for your react application
Stars: ✭ 99 (-10.81%)
Mutual labels:  hooks
Input Value
React hook for creating input values
Stars: ✭ 104 (-6.31%)
Mutual labels:  hooks
Swifthook
A library to hook methods in Swift and Objective-C.
Stars: ✭ 93 (-16.22%)
Mutual labels:  hooks
Use Substate
🍙 Lightweight (<600B minified + gzipped) React Hook to subscribe to a subset of your single app state.
Stars: ✭ 97 (-12.61%)
Mutual labels:  hooks
Ftpbucket
FTPbucket is a PHP script that enables you to sync your BitBucket or GitHub repository with any web-server
Stars: ✭ 99 (-10.81%)
Mutual labels:  hooks
Postinstall Build
Helper for conditionally building your npm package on postinstall
Stars: ✭ 87 (-21.62%)
Mutual labels:  hooks
Clean State
🐻 A pure and compact state manager, using React-hooks native implementation, automatically connect the module organization architecture. 🍋
Stars: ✭ 107 (-3.6%)
Mutual labels:  hooks
Debug Objects
WordPress Plugin for debugging and learning with and at the application.
Stars: ✭ 98 (-11.71%)
Mutual labels:  hooks
Reason Reactify
🚀 Transform a mutable tree into a functional React-like API
Stars: ✭ 102 (-8.11%)
Mutual labels:  hooks
Platform Samples
A public place for all platform sample projects.
Stars: ✭ 1,328 (+1096.4%)
Mutual labels:  hooks
Flagged
Feature Flags for React made easy with hooks, HOC and Render Props
Stars: ✭ 97 (-12.61%)
Mutual labels:  hooks
React Resize Observer Hook
ResizeObserver + React hooks
Stars: ✭ 101 (-9.01%)
Mutual labels:  hooks
React Anime
✨ (ノ´ヮ´)ノ*:・゚✧ A super easy animation library for React!
Stars: ✭ 1,313 (+1082.88%)
Mutual labels:  hooks
Rx React Container
Use RxJS in React components, via HOC or Hook
Stars: ✭ 105 (-5.41%)
Mutual labels:  hooks
Use Query Params
React Hook for managing state in URL query parameters with easy serialization.
Stars: ✭ 1,278 (+1051.35%)
Mutual labels:  hooks
Iostore
极简的全局数据管理方案,基于 React Hooks API
Stars: ✭ 99 (-10.81%)
Mutual labels:  hooks
Hooked Form
Performant 2KB React library to manage your forms
Stars: ✭ 110 (-0.9%)
Mutual labels:  hooks
Portfolio
💼 My personal portfolio built with React and three.js.
Stars: ✭ 106 (-4.5%)
Mutual labels:  hooks
Outstated
Simple hooks-based state management for React
Stars: ✭ 102 (-8.11%)
Mutual labels:  hooks

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].