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-watcher

v5.0.5

Published

The `useWatcher` React hook runs a function when a prop, state or other value changes, and gives you easy access to both the previous and next values. Think of it as the functional equivalent of `componentDidUpdate` and `getDerivedStateFromProps`.

Downloads

13

Readme

useWatcher React hook 👀

The useWatcher React hook runs a function when a prop, state or other value changes, and gives you easy access to both the previous and next values. Think of it as the functional equivalent of componentDidUpdate and getDerivedStateFromProps.

Install

npm i use-watcher

Usage

import React, {useState} from "react";
import {useWatcher} from 'use-watcher';

const Component = () => {
  const [count, setCount] = useState(0);

  useWatcher(prevCount => {
    alert(`Value changed from ${prevCount} to ${count}.`);
  }, count);

  const handleClick = () => setCount(c => c + 1);

  return (
    <>
      <div>{count}</div>
      <button type="button" onClick={handleClick}>Increment</button>
    </>
  );
};

Syntax

useWatcher(handler, value[, options])

Parameters

  • handler (function)
    A function that's called when the value has changed. Receives the previous value as only argument, and can optionally return a function that will only execute after the current render has completed (See Firing order below).

  • value (any)
    The value to watch.

  • options (object)
    An object containing additional options:

    • initialValue (any) - Default: undefined
      The value used for the initial comparison. Set to value if you don't want the handler to be triggered on first render.

    • compare (function) - Default: (prev, next) => prev === next
      The comparison function that's used to determine if the callback should be fired. Receives the previous and current values as arguments. Can be used for deep comparison, only comparing specific keys in an object, or for more exotic behavior.

Firing order

Firing a callback that leads to a parent calling setState during a render can lead to bugs and generates errors since React 16.11.

useWatcher runs the handler immediately, meaning it will run within the same render it's called in, and may cause issues when used to update parent components. That said, you can have it return a function that will only be fired after a completed render. This avoids creating side-effects during a render (which may cause unexpected behavior) and can be safely used to trigger callbacks that will update parent components. useEffect is used under the hood to achieve this safe behavior, so it's subject to the same rules.

Example

import React, {useState} from "react";
import {useWatcher} from 'use-watcher';

const ParentComponent = () => {
  const [changed, setChanged] = useState(false);

  const handleChange = () => {
    setChanged(true);
  };

  return (
    <>
      <ChildComponent onChange={handleChange} />
      <div>Changed: {changed.toString()}</div>
    </>
  );
};

const ChildComponent = ({onChange}) => {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef();

  useWatcher(
    prevCount => {
      // This runs immediately
      alert(`Value changed from ${prevCount} to ${count}. This update shouldn't be rendered yet.`);

      // `prevCountRef.current` will be updated in the same render as when `count` has changed.
      prevCountRef.current = prevCount;
      
      return () => {
        // This runs after the render where `count` has changed completes.
        alert(`Value changed from ${prevCount} to ${count}. This update should be rendered now.`);
        onChange?.();
      };
    }, 
    count
  );

  const handleClick = () => setCount(c => c + 1);

  return (
    <>
      <div>{count}</div>
      <button type="button" onClick={handleClick}>Increment</button>
    </>
  );
};