I've been developing with Hooks for a long time, But I met a situation where I was confused.
Let me briefly describe this strange problem with a particular case.
I created a very simple functional component called Test:
// test.js
export default function Test () {
useEffect(() => {
console.log('Test')
}, [])
return (
<h2>
Test Component
</h2>
)
}
It will print something at the first render
And the component will be referenced in App
// App.js
import React, { useEffect, useState } from "react";
import Test from './test';
export default function App() {
const [number, updateNumber] = useState(0);
const renderComponent = () => {
return (
<Test />
)
}
const RenderComponent = () => {
return (
<Test />
)
}
useEffect(() => {
updateNumber(1)
updateNumber(2)
}, [])
console.log('every-render')
return (
<div className="App">
{renderComponent()}
{/* <RenderComponent /> */}
<h1>Rerender times: {number}</h1>
</div>
);
}
So something strange happened
When I use this way, the Test component will be printed once
// Case 1
const renderComponent = () => {
return (
<Test />
)
}
// ...
renderComponent()
Something that it prints in Console
But when I use this way, the Test component will be printed twice
// Case 2
const RenderComponent = () => {
return (
<Test />
)
}
// ...
<RenderComponent />
Something that it prints in Console
Of course, I wrote a demo for you to debug: https://codesandbox.io/s/demo-for-hooks-8gkml?file=/src/App.js
I am confused why in case 2 the Test component will be remounted each time the Hooks are rerendered.