Created
August 14, 2024 19:34
-
-
Save bpb54321/50257a7c46865df5cbe61f2728c49af5 to your computer and use it in GitHub Desktop.
Monitor why a React component was called
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 React, { useEffect, useRef, useState } from 'react'; | |
export const Counter: React.FC = () => { | |
const [count, setCount] = useState(0); | |
const previousValueRef = useRef(count); | |
const isMountRef = useRef(true); | |
console.log('Counter called'); | |
console.log(`Previous value = ${previousValueRef.current}`); | |
console.log(`Current value = ${count}`); | |
if (isMountRef.current) { | |
console.log('Counter called because of mount'); | |
} else if (count === previousValueRef.current) { | |
console.log('Counter called because its parent updated state'); | |
} else { | |
console.log('Counter rendered because it updated state'); | |
} | |
useEffect(() => { | |
console.log('Counter mounted'); | |
isMountRef.current = false; | |
return () => { | |
console.log('Counter unmounted'); | |
}; | |
}, []); | |
useEffect(() => { | |
previousValueRef.current = count; | |
}, [count]); | |
const increment = () => { | |
setCount(count + 1); | |
}; | |
const decrement = () => { | |
setCount(count - 1); | |
}; | |
return ( | |
<div> | |
<h1>Counter</h1> | |
<p>Count: {count}</p> | |
<button onClick={increment}>Increment</button> | |
<button onClick={decrement}>Decrement</button> | |
</div> | |
); | |
}; | |
export default Counter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment