Home > OS >  Is there any difference in using React component as a (HTML tag)/ (JS function call)
Is there any difference in using React component as a (HTML tag)/ (JS function call)

Time:02-18

I have a component, something like,

const ComponentA = ({ heading })=> {
 return (<h1>{ heading }</h>);
};

Is there any difference in rendering this component using below two options,

Option 1

const ComponentB = ()=> {
 return ComponentA({ heading: 'Heading test' });
}; 

Option 2

const ComponentB = ()=> {
 return <ComponentA heading='Heading test' />;
}; 

CodePudding user response:

Yes. There is a very important difference. In option 1, ComponentA is not actually a component as far as React is concerned. In option 2 it is.

The best way to illustrate the difference is to put state or another hook inside of ComponentA. Option 1 will not work as expected. (Note: if it does happen to work as expected, you still shouldn't trust it. This is where bugs can sneak in because they don't cause issues until later).

Here is an example where using hooks appears to work, but breaks after you get the counter past 5. This is because React is treating the hooks inside ComponentA as if they belong to Example. Notice how the JSX version works as expected even after it disappears.

const {useState, useEffect} = React;

const ComponentA = ({ id, heading })=> {
   React.useEffect(() => {
    console.log(id, 'mounted');
   }, []);
 
 return (
    <h1>
      { heading }
    </h1>
  );
};

const Example = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <button onClick={() => setCount(count   1)}>Re-render me</button> {count}
      {count < 5 ? ComponentA({ heading: 'Heading test1', id: 1 }) : null}
      {count < 3 ? <ComponentA heading='Heading test2' id={2} /> : null}
    </div>
   );
}

ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

The reason is JSX (< /> syntax) is actually just a syntax for calling React.createElement. If this is not called, the function component does not get it's own lifecycle, etc. You've bypassed the way React tracks components.

  • Related