Last active
March 11, 2021 14:55
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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