How does React handle user-defined components behind the scenes?

How does React handle user-defined components behind the scenes?

ยท

2 min read

React strives to give its users the ability to build encapsulated, reusable components, but how does it manage to implement this logic in JSX?

๐Ÿ‘‰ Here is a simple example of a custom user-defined component, named Greeting, which is rendered inside a well-known App component.

Let's break them down to the simplest bits ๐Ÿ’ฅ

// Greeting.jsx
const Greeting = ({name}) => {
  return <span>Hi, {name} ๐Ÿ‘‹</span>;
}

// App.jsx
const App = () => {
  return (
    <div>
      <Greeting name="Nikita" />
    </div>
  );
}

๐Ÿ‘‰ How Greeing works?

  • Greeting is just a function, which returns ๐˜‘๐˜š๐˜Ÿ - ๐˜‘๐˜š๐˜Ÿ is syntax sugar for calling React.createElement
  • React.createElement expects type, props, and children

Let's rewrite our Greeting component with this new knowledge.

// Greeting.jsx
const Greeting = ({name}) => {
  return React.createElement(
    'span', 
    null, 
    'Hi, ', name, ' ๐Ÿ‘‹');
}

๐Ÿ‘‰ But how to use the Greeting component inside the ๐˜ˆ๐˜ฑ๐˜ฑ component?

Turns out, createElement expects three values as type:

  • tag name, like 'div' or 'span'
  • a class or a function, that defines custom component
  • React fragment type
// App.jsx
const App = () => {
 return React.createElement(
   'div',
   null,
   React.createElement(Greeting, {name})
 );
}

๐Ÿ‘‰ Simply put, createElement calls the passed function internally and uses its return value to form the component tree.

// Internal intermediate result
const App = () => {
 return React.createElement(
   'div',
   null,
   React.createElement(
     'span', 
     null, 
     'Hi, ', 'Nikita', ' ๐Ÿ‘‹'
   )
 );
}

๐Ÿ‘‰ Verify that it works yourself!

Go to reactjs.org, open the console and paste the last code snippet there.

Then call the App() and see the end result. If it's the same as here ๐Ÿ‘‡, you've done a great job!

result.png

P.S. For more bite-sized in-depth content like this, follow me on Twitter

ย