I'm somewhat new to react, and I'm trying to learn when every time a component will re-render. Usually I'm good at figuring this stuff out on my own, but I can't seem to find the logic in these
Exhibit A
const Science = () => {
console.log('Rendering')
useEffect(() => console.log('Effect ran'))
console.log('Returning')
return <div></div>
}
This outputs
Rendering
Returning
Rendering
Returning
Effect ran
I don't understand why it re-renders, and why the useEffect code comes after both renders and returns.
Exhibit B
const Science = () => {
console.log('Rendering')
useEffect(() => console.log('First effect ran'))
useEffect(() => console.log('Second effect ran'))
console.log('Returning')
return <div></div>
}
This outputs
Rendering
Returning
Rendering
Returning
First effect ran
Second effect ran
My guess to why it re-renders in Exhibit A was that useEffect causes a re-render, but seen here, only one useEffect will cause a re-render. Unsure of this behavior.
Exhibit C
const Science = () => {
console.log('Rendering')
let numRenders = useRef(0)
console.log(++numRenders.current)
console.log('Returning')
return <div></div>
}
This one really confuses me, as it outputs
Rendering
1
Returning
Rendering
1
Returning
I don't understand why on the second render, it doesn't increment. I know that it does permanently increment the value, and not just for the logging.
Thanks.