Reputation: 25
Can someone explain the difference in calling a JSX Element as component and as function in react?
These are my functions.
Case-1: as a function
const MyFunction = () => {
return (
<div>Hello</div>
)
}
and calling it as
<Parent>
MyFunction()
</Parent>
Case-2: as a react functional component
const MyFunction:React.FC = ():JSX.Element => {
return (
<div>Hello</div>
)
}
and calling it as
<Parent>
<MyFunction />
</Parent>
can someone please explain, if there really is a difference or not?
Upvotes: -1
Views: 46
Reputation: 85151
If you call it as a function, then it's not really a component. It's just more code that's part of this component. I recommend you don't do this, and react also recommends you don't do this. If you do anyway, you must be very careful to make sure you're following the rules of hooks, which either means MyFunction
cannot call any hooks, or you must call MyFunction
exactly the same number of times every time you render.
If you create an element (<MyFunction />
), then you are creating an instruction which asks react to render the component. After your current component finishes rendering, react will call MyFunction
. Since react is calling MyFunction
, it can set up all the internal state needed for hooks, so MyFunction
can freely call whichever hooks it likes, even if multiple <MyFunction />
's are being rendered.
Upvotes: 1