Skip to content

Instantly share code, notes, and snippets.

@bpb54321
Last active March 11, 2021 14:55
Show Gist options
  • Save bpb54321/9f7af88166ebeccd4e26da6c20b5641e to your computer and use it in GitHub Desktop.
Save bpb54321/9f7af88166ebeccd4e26da6c20b5641e to your computer and use it in GitHub Desktop.
Custom React Hook for tracking when a given value changes, which would cause a component to re-render. Should be called for every prop or state value in a component if you want to figure out what is causing a re-render.
import { COUNT_INCREMENTED } from "./countReducer";
import useCount from "./useCount";
import useValueDifference from "./useValueDifference";
const Counter = () => {
console.log("Counter");
const [count, dispatchCount] = useCount();
useValueDifference({ count });
return (
<>
<h2>Counter</h2>
<p data-testid="count">{count}</p>
<button onClick={() => dispatchCount(COUNT_INCREMENTED)}>
Increment
</button>
</>
);
};
export default Counter;
import { useRef } from "react";
function useValueDifference(newValueObject) {
const oldValueObjectRef = useRef(newValueObject);
const oldValueObject = oldValueObjectRef.current;
for (const key of Object.keys(newValueObject)) {
const oldValue = oldValueObject[key];
const newValue = newValueObject[key];
if (!Object.is(oldValue, newValue)) {
console.log(`"${key}" changed from`);
console.log(oldValue);
console.log("to");
console.log(newValue);
}
}
oldValueObjectRef.current = newValueObject;
}
export default useValueDifference;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment