@lucarestagno/use-deep-effect
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

use-deep-effect 🕵️‍♂️

React useEffect is built to work with primitive values in the dependencies array.

It could happen that in your reach application you need to run side effects based on complex objects (Objects, Arrays, Sets, Maps).

In all these cases, you can use useDeepEffect.

Installation

npm i @lucarestagno/use-deep-effect

Usage

import React from 'react'
import ReactDOM from 'react-dom'
import useDeepEffect from 'use-deep-effect'

const MyComponent = ({ arrayOfObjects }) => {
  useDeepEffect(() => {
    /* side effect */
  }, 
  [arrayOfObjects])

  return </>
}

Custom comparison function

By default, useDeepEffect uses fast-deep-equal as comparison function, but you can use your custom function by passing it as third argument.

useDeepEffect(fn, dependencies, comparisonFunction)

Why useEffect only works with primitive values?

useEffect uses Object.is to compare the dependencies.

This makes it perfectly working with primitive values (number, string, boolean), bot not with complex types (array, object, set, map).

For instance, this equality check returns false even if the two objects own the same keys and values:

Object.is({ foo: 'foo' }, { foo: 'foo' });
false

Or they are the same array

Object.is([1, 2, 3], [1, 2, 3]);
false

You can use useDeepEffect, but remember that it comes with a performance cost (often negligible).

Readme

Keywords

Package Sidebar

Install

npm i @lucarestagno/use-deep-effect

Weekly Downloads

85

Version

1.0.7

License

MIT

Unpacked Size

6.48 kB

Total Files

6

Last publish

Collaborators

  • ikoichi2112