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
6
Maintainers
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 tovalue
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>
</>
);
};