The Wayback Machine - https://web.archive.org/web/20240906065213/https://www.geeksforgeeks.org/reactjs-functional-components/
Open In App

ReactJS Functional Components

Last Updated : 21 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Functional Component is one way to create components in a React Application. React.js Functional Components helps to create UI components in a Functional and more concise way. In this article, we will learn about functional components in React, different ways to call the functional component, and also learn how to create the functional components. We will also demonstrate the use of hooks in functional components

Functional Components in React :

ReactJS Functional components are some of the more common components that will come across while working in React. These are simply JavaScript functions. We can create a functional component in React by writing a JavaScript function. These functions may or may not receive data as parameters. In the functional Components, the return value is the JSX code to render to the DOM tree.

Ways to call the functional component:

We can call the functions in javaScript in other ways as follows:

1. Call the function by using the name of the function followed by the Parentheses.

// Example of Calling the function with function name followed by Parentheses
function Parentheses() {
return (<h1>
We can call function using name of the
function followed by Parentheses
</h1>);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(Parentheses());

2. Call the function by using the functional component method.

// Example of Calling the function using component call
function Comp() {
return (<h1> As usual we can call the function using component call</h1>);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Comp />);

Now, We will use the functional component method to create a program and see how functional components render the component in the browser.

Steps to create the React application:

Step 1: Create React Project 

npm create-react-app myreactapp

Step 2: Change your directory and enter your main folder charting as

cd myreactapp

Project Structure:

Screenshot-from-2023-10-06-09-44-29

Example 1: This example demonstrates the creation of functional components.

Javascript




// Filename - index.js
 
import React from "react";
import ReactDOM from "react-dom";
import Demo from "./App";
 
const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(
    <React.StrictMode>
        <Demo />
    </React.StrictMode>
);


Javascript




//Filename - App.js
 
import React from 'react';
import ReactDOM from 'react-dom';
 
const Demo=()=>{return <h1>Welcome to GeeksforGeeks</h1>};
export default Demo;


Step to run the application: Open the terminal and type the following command.  

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

ReactJS Functional Components

Problem with using functional components

Functional components lack a significant amount of features as compared to class-based components and they do not have access to dedicated state variables like class-based components.

Advantage of using hooks in functional components

The problem discussed above is solved with the help of a special ReactJS concept called “hooks”. ReactJS has access to a special hook called useState(). The useState() is used to initialize only one state variable to multiple state variables. The first value returned is the initial value of the state variable, while the second value returned is a reference to the function that updates it.

Example 2: This example demonstrates the use of useState() hook in functional component.

Javascript




// Filename - index.js
 
import React from "react";
import ReactDOM from "react-dom";
import Example from "./App";
 
const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(
    <React.StrictMode>
        <Example />
    </React.StrictMode>
);


Javascript




// Filename - App.js
 
import React, { useState } from "react";
 
const Example = () => {
    const [change, setChange] = useState(true);
    return (
        <div>
            <button onClick={() => setChange(!change)}>
                Click Here!
            </button>
            {change ? (
                <h1>Welcome to GeeksforGeeks</h1>
            ) : (
                <h1>A Computer Science Portal for Geeks</h1>
            )}
        </div>
    );
};
export default Example;


Step to run the application: Open the terminal and type the following command.  

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

ReactJS Functional Components

Functional components do not have access to lifecycle functions like class-based components do since lifecycle functions need to be defined within the boundaries of a class. A special React hook called useEffect() needs to be used. It is worth noting that useEffect() isn’t an exact duplicate of the lifecycle functions – it works and behaves in a slightly different manner.

Example 3: This example demonstrates the use of useEffect() hook.

Javascript




// Filename - index.js
 
import React from "react";
import ReactDOM from "react-dom";
import Example from "./App";
 
const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(
    <React.StrictMode>
        <Example />
    </React.StrictMode>
);


Javascript




// Filename - App.js
 
import React, { useEffect } from "react";
 
const Example = () => {
    useEffect(() => {
        console.log("Mounting...");
    });
    return <h1>Geeks....!</h1>;
};
export default Example;


Step to run the application: Open the terminal and type the following command.  

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

ReactJS Functional Components

Data is passed from the parent component to the child components in the form of props. ReactJS does not allow a component to modify its own props as a rule. The only way to modify the props is to change the props being passed to the child component. This is generally done by passing a reference of a function in the parent component to the child component.

Example 4: This example demonstrates the use of props.

Javascript




// Filename - index.js
 
import React from "react";
import ReactDOM from "react-dom";
import PropsExample from "./App";
 
const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(
    <React.StrictMode>
        <PropsExample />
    </React.StrictMode>
);


Javascript




// Filename - App.js
 
import React, { useState } from "react";
 
const Example = (props) => {
    return <h1>{props.data}</h1>;
};
const PropsExample = () => {
    // const [change, setChange] = useState(true);
    const [change, setChange] = useState(false);
    return (
        <div>
            <button onClick={() => setChange(!change)}>
                Click Here!
            </button>
            {change ? (
                <Example data="Welcome to GeeksforGeeks" />
            ) : (
                <Example data="A Computer Science Portal for Geeks" />
            )}
        </div>
    );
};
export default PropsExample;


Step to run the application: Open the terminal and type the following command.  

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

ReactJS Functional Components



Previous Article
Next Article

Similar Reads

Differences between Functional Components and Class Components
In this article, we will learn about the differences between functional and class components in React with the help of an example. We will create a counter and implement it using both class and functional components to understand the differences practically. Functional Components Functional components are some of the more common components that wil
4 min read
Why it is Recommended to use Functional Components over Class Components ?
In this article, we will learn about the use of the functional component over the class component. In React JS, there are two main types of components:  Functional Components Class Components.Functional Components are JavaScript functions that take in props as an argument and return a React element to be rendered. They are simpler and less verbose
4 min read
Migrating from Class Components to Functional Components in React
React version 16.8.0 or higher allows users to write the functional components without the use of class components. Using class components, we need to write the whole class to interact with the state and lifecycle of the component. The code was quite complex and harder to understand which led to lower performance and limited usability. With the hel
4 min read
How to change states with onClick event in ReactJS using functional components ?
In modern web applications, to change states with onClick event in React JS using functional components is done by Hooks in React as the functional components don't have inbuilt states like class components. With Hooks, state objects are completely independent of each other, so you can have as many state objects as you want. In a single-page applic
2 min read
How to Create Functional Components using Vue Loader ?
Vue.js is a JavaScript framework used in building powerful and beautiful user interfaces. The key feature of Vue.js is its component-based architecture that allows the developers to create reusable and modular components. Functional components, in particular, provide a lightweight and efficient way to build UI elements. In this article, we will lea
3 min read
Why do you need to import React in functional components ?
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. In react, we use JSX, especially in the functional important which is an extension of Javascript it needs the react met
3 min read
Advantages of using Functional Components in React
Functional components in React are like a quick and easy way to create pieces of your web app. They're simple, straight to the point, and don't involve a lot of extra code. Think of them as building blocks that help you put together your app without any unnecessary complications. Advantages of using functional components in React:Simplicity: Functi
2 min read
How to create Functional Components in React ?
To create a functional component in React, you define a JavaScript function that returns JSX. These components are stateless and rely on props for data input. Functional components are concise, easy to read, and can utilize React Hooks for managing state and side effects, making them a fundamental building block for React applications. Prerequisite
2 min read
Role of Hooks in Functional Components.
Hooks in React are like new tools that make building components easier. Before, we had to use classes, which were like following strict instructions. But with hooks, we can do the same thing more simply and flexibly directly inside functional components. It's like having a magic connector for building React components, allowing us to manage state,
3 min read
How does React.memo() optimize functional components in React?
React.memo() is a higher-order component provided by React that can help optimize functional components by reducing unnecessary re-renders. Let's explore how it works and how it optimizes functional components: Table of Content Optimizing with React.memo()When to use React.memo() ?Benefits of memoization using React.memo()How to use React.memo() ?C
4 min read
Advantages of using Functional Components with React Hooks
In the past, React mainly used class-based components as its building blocks. However, functional components, which are essentially JavaScript functions that receive props (inputs) and return JSX (rendered content), were limited in their capabilities. With React 16.8 and the introduction of hooks, functional components gained access to features lik
4 min read
Implementing Lazy Loading for Functional Components in React
React is a popular library, maintained by Meta, which is used for building user interfaces and dynamic websites. It offers several techniques to optimize performance and enhance end-user experience. Lazy loading is one such technique that can be used to improve the performance of web applications by deferring the loading of resources until the brow
2 min read
What is a pure functional component in ReactJS ?
What is a JavaScript function? A JavaScript function is a block of code designed to perform a particular task which is executed when it is called. How React functional components are similar to JavaScript functions? Conceptually, components are like JavaScript functions. A functional component is a JavaScript function that returns JSX in React. The
3 min read
How to convert functional component to class component in ReactJS ?
ReactJS offers two primary ways of creating components: functional components and class components. While functional components are more concise and easier to reason about, there are situations where class components may be necessary with the flexibility to use lifecycle methods and manage the state in a different way. PrerequisitesReact JSReact Fu
2 min read
How to get previous state in ReactJS Functional Component ?
To get the previous state in ReactJS Functional Component we can use the previous value of the state while using the set state method. State can only be directly accessed in the class component so we will be using the react useState hook to accomplish the task. PrerequisitesReact JSReact JS functional componentsReact useState HookSteps to create Re
2 min read
How to access props.children in a stateless functional component in ReactJS ?
The {props. children} allows you to create a generic template, which can be modified by a parent when invoked. In this way, a parent component can easily pass whatever is necessary to its child, even generated layout features. Anytime you call a component, it automatically displays whatever it has between its opening and closing tags. A component w
5 min read
How do Styled Components work in terms of styling React components?
Styled Components is a library for React and React Native that allows you to write CSS in your JavaScript code in a more component-oriented way. Working of Styled Components:Component-Based Styling: Styled Components allow you to write actual CSS directly into your JavaScript files using tagged template literals. This means you can define styles fo
2 min read
Use nested Components With Standalone Components in Angular 17
Angular 17 introduced a new feature called Standalone Components, which allows you to create self-contained components that can be used independently without being tied to a specific module. This feature can make your code more modular and easier to maintain. However, when working with Standalone Components, you might need to nest components within
3 min read
ReactJS | Components - Set 2
In our previous article on ReactJS | Components we had to discuss components, types of components, and how to render components. In this article, we will see some more properties of components. Composing Components: Remember in our previous article, our first example of GeeksforGeeks's homepage which we used to explain components? Let's recall what
3 min read
How to map data into Components using ReactJS?
Map all individual custom pieces of data to the custom component. For example: Instead of writing custom components again and again with different props. I will make an array that contains all props and use the map() function to map the array element with a custom component in a single component call. A map is a data collection type where data is s
3 min read
ReactJS Components Complete Reference
Components are bits of code that are freelance and reusable. They serve a similar purpose as JavaScript functions. However, work isolation and returns HTML via a render function. A Component is one of the core building blocks of React. In other words, we can say that every application you will develop in React will be made up of pieces called compo
2 min read
How to put an image as background under multiple components in ReactJS with React Routing?
We can make a parent component and use that parent component to wrap the child component so that the parent component appears as an image overlay above the child component. Syntax: &lt;div style={{ backgroundImage: `url(${'/background.jpg'})`}}&gt; {props.children} &lt;/div&gt; Creating React Application: Step 1: Create a React application using th
2 min read
ReactJS Server Components
React is a JavaScript library which is used to develop frontend of websites. Since it's introduction in the year 2013 React has gained a lot of popularity among the web developers around the world. The library has a great support from the community and is evolving at a high speed from its launch. In 2022 React released an update in which server com
3 min read
Controlled vs Uncontrolled Components in ReactJS
In React, Controlled components refer to the components where the state and behaviors are controlled by Parent components while Uncontrolled components are the ones having control of their own state and manage the behaviors on themselves. Table of ContentUncontrolled ComponentsControlled ComponentsDifference between Controlled and Uncontrolled Comp
3 min read
What are Controlled components in ReactJS ?
React's Controlled Components manage form data via component state, receiving values through props and updating through callbacks like onChange. The parent component maintains the state, passing updated values as props to the controlled component. Form elements, whether typed (e.g., textarea, input) or selected (e.g., radio buttons, checkboxes), tr
2 min read
What is typical pattern for rendering a list of components from an array of data in ReactJS ?
The pattern for rendering a list of components from an array of data can be done by mapping all individual custom pieces of data to the component. With the map function, we will map every element data of the array to the custom components in a single line of code.  Prerequisites:NodeJS or NPMReact JSSteps to Create the React Application:Step 1: Cre
2 min read
How to create components in ReactJS ?
Components in React JS is are the core of building React applications. Components are the building blocks that contains UI elements and logic, making the development process easier and reusable. In this article we will see how we can create components in React JS. Table of Content React Functional ComponentsReact Class-based Components Rendering th
3 min read
ReactJS Web Components
Web components, encapsulated HTML tags for web development, are versatile, framework-agnostic elements native to HTML, usable seamlessly in various environments like React and Angular. What are the types of web components?There are three types of web components: Table of Content What are the types of web components?Custom ElementsShadow DOMHTML Tem
4 min read
How are React Hooks different from class components in ReactJS?
React Hooks are helpful tools that make building websites and apps with React easier. They simplify how users handle things like data and app behavior, making the code cleaner and easier to understand. Class components in React are like the old-school way of building parts of your website or app. They use JavaScript classes to structure components,
2 min read
ReactJS Container and Presentational Pattern in Components
In this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of components is decided by components pattern. If the comp
2 min read