What are Components in React?

What are Components in React?

React is a popular open-source javascript library used to create web applications and was created by Facebook.

It is based on a component-based architecture that enables one to build complex user interfaces by breaking them down into small, reusable components. This makes it easy to develop and maintain complex user interfaces, and also makes it easier to reuse components across different parts of an application.

In this article, we will discuss what React components are, how they work, and why they are important.

So, just what are React components?

They are small, reusable pieces of code that define the structure and behavior of a part of a user interface.

Here's an illustration of how a basic app ui structure would look like

It comprises 4 components namely; Header, Side Nav, Main Content and Footer. The four are contained in the Root component which is named the App component.

Types of Components:

i) Class component

ii) Function component

i) Class components

Class components are ES6 javascript classes that return JSX.

It was the most popular of building React applications before the introduction of Hooks in version 16.8. They essentially start with a class keyword that extends the Component constructor from React and has a render method that returns a JSX. The below code returns Hello World!

class HelloWorld extends React.Component { 
  render() { 
    return <h1>Hello World!</h1>; 
  } 
}

ii) Function components

Being the most preferred component nowadays: A Functional Component is a type of component that uses JavaScript function to create React component.

They start with the function keyword. The same code as before can be expressed as:

function HelloWorld() { 
  return <h1>Hello world</h1>; 
}

Some advantages of components are;

1. Reusability

Each component can be used many times in the project with each being independent of the other and the whole UI.

2. Testability

It is easy to check on each part differently and diagnose with components being independent rather than trying to figure out the whole system at once.

3. Update just one component

Every React component acts separately, you can change one section of the application without needing to update everything.

All in all, components are a great way to make user interfaces and this article gave a brief introduction to the world of components.