Do you know React Component, Instance, and Element?

Do you know React Component, Instance, and Element?

In this article, we will explore the fundamental concepts of React, gaining an understanding of React components, instances, and elements, which collectively form the building block of creating user interfaces (UI) in React.

Component

In React components are reusable, self-contained units of UI, encapsulating a specific piece of functionality. There are two types of components: Class components and Functional components. However, in this case, we will focus on Functional components as it is the preferred and concise way to define React components.

A Functional component is similar to a JavaScript function that returns React elements in the form of JSX (JavaScript XML) as output.

Code Example

function UsersInformation() {
  return (
    <div>
      <h1>Users Information</h1>
      <p>Name: John Bill</p>
      <p>Age: 25 years old</p>
    </div>
  )
}

Instance

When we use a component by calling the component with parentheses, it creates an instance of that component and instances have their own state, props, and lifecycle.

Code Example

export default function App() {
  return (
    <div>
      <UsersInformation />  //Instance
    </div>
  );
}

Element

In React each instance returns one or more React elements.

React elements are JavaScript objects that define what should be displayed on the screen. Behind the scenes, JSX is converted to React.createElement() function calls, resulting in the creation of React elements.

React elements are immutable, meaning they cannot be modified once they are created.

Code Example

{$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}
$$typeof : Symbol(react.element)
key : null
props : {}
ref : null
type : ƒ UsersInformation()
length : 0
name : "UsersInformation"
prototype : {}
arguments : (...)
caller : (...)
[[FunctionLocation]] :  App.js:30
[[Prototype]] : ƒ ()
[[Scopes]] : Scopes[3]
_owner : null
_store : {validated: false}
_self : undefined
[[Prototype]] : Object

Summary

  • Component: Defines the behavior and structure of a reusable UI element.

  • Instance: Represents an individual occurrence of a component within the React application, managing its own props, state, and lifecycle methods.

  • Element: Describes a virtual DOM node representing a React component, created using JSX or React.createElement().

When a React component is rendered, it creates an instance that corresponds to a specific element in the virtual DOM. This element is then reconciled with the actual DOM, resulting in the creation of the corresponding UI on the screen.