-1

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?

2
  • stackoverflow.com/questions/58656026/… Commented May 21, 2024 at 14:42
  • Please edit the question so that the title "summarizes the problem" (from How to Ask). Currently it is simply the name of a tag and does not help to understand the question. Commented May 21, 2024 at 14:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.