Back
React
Thu Jul 25 2024

Essential Built-in components in React

Introduction to components

React components are reusable code segments that correspond to specific user interface elements. Components are independent, meaning they have their own structure, styling, and behavior. They can be either class-based or function-based and can be nested within each other to create complex UIs from simpler building blocks.

For instance, if we were building the UI of an e-commerce website using React, we could break the entire website into smaller parts like Home, About, Login, Cart, etc. Each of these parts can be created separately as components in React. Components also interact with each other through props (which are inputs to a component) and manage their own state to handle dynamic data. 

In this blog, we'll look at some built-in components of React that can help make the development process simpler and more efficient. These features can help you create more efficient, maintainable, and efficient apps. 

Built-in components

React provides several built-in components that helps us build user interface more easily and efficiently. They handle common tasks and follow declarative style of React. Some of the built-in React components are described below.

Fragment

The Fragment component in React allows us to group multiple elements without adding an extra node to the DOM. This kind of grouping is useful when you need to return multiple elements from a component without introducing additional wrapper elements, which can be beneficial for styling and performance.

You can use the Fragment component in two ways:

  • Using <Fragment>...</Fragment>
  • Using the shorthand JSX syntax <>...</>

Implementation

//App.js
import Form from "./Form";
import "./App.css";
import User from "./User";

function App() {
  const user1 = {
    name: "John Doe",
    email: "[email protected]",
    address: {
      province: "3",
      city: "Kathmandu",
    },
  };

  const user2 = {
    name: "Pooja Sharma",
    email: "[email protected]",
  };

  return (
    <div>
      <h1>User profiles</h1>
      <User user={user1} />
      <User user={user2} />
    </div>
  );
}

export default App;
//User.js
import React, { Fragment } from "react";

function User({ user }) {
  return (
    <div>
      <h1>Name: {user.name}</h1>
      <p>Email:{user.email}</p>
      {user.address && (
        <Fragment>
          <h3>Address</h3>
          <p>{user.address.province}</p>
          <p>{user.address.city}</p>
        </Fragment>
      )}
    </div>
  );
}

export default User;

In the above example, the Fragment component is used in the User component to group multiple elements (h3 and p elements) without adding an extra wrapper node to the DOM. This ensures that the additional address information is only included in the DOM if the user.address property is present, and it does so in a clean and efficient manner.

 

Profiler

The Profiler component in React helps the developers in measuring the performance of their React applications by collecting timing information about each component. This component identifies which components are rendering slowly or too frequently. By knowing the components' rendering time, developers are able to optimize the performance of their React applications.

The Profiler component contains two props. They are:

  •  'id' : It is a string identifier for the Profiler.
  • 'onRender' : It is a callback function that receives the performance data like phase, id, actualDuration, baseDuration, startTime, commitTime and interactions.

Implementation

import "./App.css";
import User from "./User";
import { Profiler } from "react";

function App() {
  const onRenderCallback = (
    id,
    phase,
    actualDuration,
    baseDuration,
    startTime,
    commitTime,
    interactions
  ) => {
    console.log(`Profiler id: ${id}`);
    console.log(`Phase: ${phase}`);
    console.log(`Actual Duration: ${actualDuration}`);
    console.log(`Base Duration: ${baseDuration}`);
    console.log(`Start Time: ${startTime}`);
    console.log(`Commit Time: ${commitTime}`);
    console.log(`Interactions: ${interactions}`);
  };

  const user1 = {
    name: "John Doe",
    email: "[email protected]",
    address: {
      province: "3",
      city: "Kathmandu",
    },
  };

  const user2 = {
    name: "Pooja Sharma",
    email: "[email protected]",
  };

  return (
    <div>
      <h1>User profiles</h1>
      <Profiler id="User1" onRender={onRenderCallback}>
        <User user={user1} />
      </Profiler>
      <Profiler id="User1" onRender={onRenderCallback}>
        <User user={user2} />
      </Profiler>
    </div>
  );
}

export default App;

In the above example, we use the Profiler component on already defined components to measure the performance of those components. We can see the unique id, phase, actualDuration it was mounted or rendered, baseDuration, startTime, commitTime and interactions.

 

StrictMode

StrictMode is a tool in React that helps developers write resilient applications by identifying potential issues in an application. It lets us find common bugs in our components early during development. We can use StrictMode for an entire app or in any part of our application. It is a component that can be wrapped around other components to enable additional checks and warnings during the development phase. StrictMode doesn't render any visible UI and has no effect in production builds.

Implementation

<StrictMode>

<App />

</StrictMode>

 

Suspense

In React, Suspense is used to enhance the user experience by displaying fallback content while the data is being loaded. All the components inside a Suspense boundary are treated as a single unit which means the components will appear together once all of them are ready. If any one of the component is still loading, the fallback component is shown.

Implementation

//App.js
import "./App.css";
import User from "./User";
import { Profiler } from "react";
import { Suspense } from "react";

function App() {
  const LoadingSpinner = () => <div>Loading...</div>;

  return (
    <div>
      <h1>User profiles</h1>
      <Profiler id="User1">
        <Suspense fallback={<LoadingSpinner />}>
          <User />
        </Suspense>
      </Profiler>
    </div>
  );
}

export default App;
//User.js
import React from "react";

const fetchUserData = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        name: "John Doe",
        email: "[email protected]",
        address: { province: "3", city: "Kathmandu" },
      });
    }, 2000);
  });
};

let user = null;
let promise = null;

const fetchUserResource = () => {
  if (!user && !promise) {
    promise = fetchUserData().then((data) => {
      user = data;
    });
  }
  if (user) {
    return user;
  } else {
    throw promise;
  }
};

const User = () => {
  const user = fetchUserResource();
  return (
    <div>
      <h1>Name: {user.name}</h1>
      <p>Email: {user.email}</p>
      {user.address && (
        <>
          <h3>Address</h3>
          <p>{user.address.province}</p>
          <p>{user.address.city}</p>
        </>
      )}
    </div>
  );
};

export default User;

In the above example, the App component wraps the User component in a Suspense boundary with a loading spinner as the fallback. The User component simulates fetching user data with a delay, and Suspense handles the loading state, displaying user details once the data is fetched.

 

Conclusion

React apps are centered around components, which let developers construct sophisticated user interfaces from basic, reusable parts. One way to keep the codebase tidy and modular is to divide a user interface into smaller, more manageable components, such as Home, About, Login, and Cart. Through the use of these built-in components in React applications, we can improve user experience, performance, and code organization. The declarative approach of React and these components make it easier to build robust and efficient application.