React

JSX

JSX is a syntax in React that allows us to create HTML elements using JavaScript (or TypeScript) programmatically. It enables us to use if statements to dynamically show and hide elements.

Code Example

0 1 2 3 4 5 6 7 8 9 10 import React from 'react'; const Greeting: React.FC<{ name: string }> = ({ name }): JSX.Element => { return ( <div> <h1>Hello {name ? name : 'world'}!</h1> </div> ); };

Here we see a functional component called Greeting of type React.FC<{ name: string }>. It receives a name as a prop and returns a JSX.Element.

The React.FC<{ name: string }> specifies that the function is a functional component, and it receives a prop object of type { name: string }.

The JSX.Element indicates that the function returns a JSX element that can be used inside other JSX elements.

Inside, the function returns a <div> with an <h1> element that renders Hello *name_value*! or Hello world!, depending on whether the name prop is defined.

Basic Rendering

React is a library that makes adding, modifying, and removing HTML elements from the DOM very quick and easy programmatically. Doing this is called rendering, and it involves a few steps:

  1. Triggering a render.
  2. Rendering the component.
  3. Committing to the DOM.

Render Trigger

A React component can be triggered in two different ways. One is the initial render trigger when the component is called for the first time. The second is when the component or its parent has a change of state. Updating an element will trigger the update of all of its children. “Triggering“ an update actually means adding the render update function to a queue.

Rendering the component

Once an update is triggered, the component's update function is added to the queue. If it has children, their update functions are also added to the queue. This process is recursive: if an updated component returns another component, that component will update too.

Committing to the DOM

For the initial render, React uses the appendChild() function to add all the nodes to the DOM. When a component update occurs, React is smart enough to avoid using appendChild() on all the nodes. It only changes the ones that are different.

🏛️ 🧮 📝 ⚛️ 🏠