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

1.0.0 • Public • Published

useChangeEffect

build status

Run an effect when a value changes. Useful when you want to:

  • Know when a prop, state, or other value changes.
  • Know what the previous value was.
  • Avoid running the effect on mount.

Installation

$ npm install --save @ehynds/use-change-effect

# or

$ yarn add @ehynds/use-change-effect

Usage

import { useChangeEffect } from '@ehynds/use-change-effect';

const Component = ({ loading }) => {
  useChangeEffect(
    (prevLoading) => {
      console.log(`loading changed from ${prevLoading} to ${loading}`);
    },
    [loading]
  );

  ...
}

If the dependencies array contains multiple values, each previous value is passed to the effect as separate arguments:

useChangeEffect(
  (prevLoading, prevError) => {
    console.log('loading and/or error changed', { prevLoading, prevError });
  },
  [loading, error]
);

Package Sidebar

Install

npm i @ehynds/use-change-effect

Weekly Downloads

109

Version

1.0.0

License

MIT

Unpacked Size

7.74 kB

Total Files

10

Last publish

Collaborators

  • ehynds