Yau Don
Yau Don

Reputation: 40

What is the difference between rendering from a JSX and from a function?

Consider the following:

const Foo = ({ bar }) => {
  return (
    <div>
      {bar}
    </div>
  )
}

What is the difference between <Foo bar='something' /> and Foo({ bar: 'something' })?

render (
  <>
    {/* Is there any difference for the following two? */}
    <Foo bar='something' />
    {Foo({ bar: 'something' })}
  </>
);

Upvotes: 1

Views: 83

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74695

When you call Foo({ bar: 'something' }), and render the result in your component, then you are essentially no longer treating Foo as its own React component, and instead assimilating it into the calling component. In effect, it would be the same as putting the result of calling the function inline in the parent component.

On the other hand, when you use <Foo> in JSX syntax, or equivalently, React.createElement(Foo), then Foo is treated as its own component, which means that it can make use of features like React Hooks.

In the simplest case as you have shown, there is really no difference, but in practice, it generally makes sense to use the JSX syntax.

Upvotes: 1

staycalm 1998
staycalm 1998

Reputation: 41

This expects the foo function is going to return an UI (e.g. Card, div).

<Foo bar ='something'/>

This does not expect the foo function to return an UI, ONLY RUN THE FUNCTION WITHIN IT.

<Foo({bar:'something'})

Upvotes: 0

Related Questions