Skip to content

Instantly share code, notes, and snippets.

@danedavid
Created June 19, 2020 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danedavid/65d0720a0141282e9f60c8e0fdb4f2ea to your computer and use it in GitHub Desktop.
Save danedavid/65d0720a0141282e9f60c8e0fdb4f2ea to your computer and use it in GitHub Desktop.
Custom React hook for fetching previous props & state values
/* Usage */
const Counter = ({ upperCount }) => {
const [count, setCount] = useState(1);
usePrevValues(
{
count,
upperCount
},
prevValues => {
if (prevValues.count + 1 === count) {
console.log("state change");
}
if (prevValues.upperCount + 1 === upperCount) {
console.log("prop change");
}
}
);
return (
<>
<div>upper count: {upperCount}</div>
<div>inner count: {count}</div>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
};
const usePrevValues = (value, callback) => {
const prevValues = useRef(value);
useEffect(() => {
callback(prevValues.current);
return () => (prevValues.current = value);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment