As a beginner to Functional Component, in this article you will get an idea about types of React components and why to choose Functional Component over class component, and the benefits of Functional Component.
As we all know, React.js is open-source JavaScript library which is used for building user interface. React is faster and is used to develop a single page or mobile application. It also allows us to create reusable UI Components. Components are reusable building blocks, reusing the components would make less code and more readable.
There are two types of components,
- Class Component
- Functional Component
The Class Component is a simple class with props, state, and lifecycle components. The advantage of the class component is the Lifecycle method.
The Functional Component is a plain JavaScript function without state or lifecycle hooks. The Functional Component is also known as the stateless component. Both components contain different syntax to use.
The Functional Component accepts props as an argument and returns valid JSX. JSX allows us to write HTML inside react.
It is also called stateless because it is like a function and it takes an input prop and returns the output as React element.
Why Functional Component?
- The Functional Component is much easier to read, test and debug, it is a plain JavaScript function.
- It has less code which makes it more readable.
- There are no render methods used in the Functional Component.
- After React 16, Functional Component capable of using hooks like useState, useEffect, etc.
Create a sample Hello world in Functional Component
Import React from reacting package,
- import React from"react";
Now we will write a function to display a simple Hello world,
- function App(){
- const sample="Hello World!";
- return<h1>{sample}</h1>;
- }
In the above code, we have created a function to display a String, "Hello World." There is no render method in the Functional Component, it returns a valid JSX element.
This is the result of our code,
- import React from"react";
- function App(){
- const sample="Hello World!";
- return<h1>{sample}</h1>;
- }
- export default App;
So, this is how we can create a simple Hello World program in the Functional Components. We could use this Functional Component for developing presentational components.
I hope this article was helpful.
Thank you for reading!