Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

React Functional Components with Examples [In-Depth Guide]

Updated on 28 October, 2024

32.89K+ views
19 min read

If you are a web developer and working in React, you probably heard about React components. It is the core building block of any React application. Every react application contains at least one base component.  

React components can be divided into two types, class components and functional components. This article will discuss everything you need to know about the react functional components. We will begin with what are react components? What are functional components? How to create states in functional components? React lifecycle methods in functional components? We will also answer some of the Frequently Asked Questions (FAQs).

What is React Functional Components?

React functional components are just normal JavaScript functions; we can create them using specific function keywords. Most developers create functional components using the Arrow function. The functional component’s primary purpose is to render the view and the data to the browser.

In other words, functional components accept data, or more technically, it takes props as a function argument and returns the data in valid JSX form.  

Below is the example for a react functional component props as an argument and returns the support in the valid JSX form.

export default function Greeting(props) {
    return (
        <div>
            Good morning! {props.name}.
        </div>
    )
}

In real-world applications, passing the props to the functional components is expected. Props are an integral part of every react application. It gives information from one component to another, which helps us build dynamic and robust applications.

One thing to note here is that props are read-only, which means that the React components need not change their values and that the same props return the same value. The components which follow this pattern are called Pure components, and in other words, functional components are pure components. 

Ways to Call the React Functional Component

React functional components are essential building blocks in React applications, allowing developers to create reusable and manageable pieces of UI. There are several ways to call or invoke functional components in React:

A. Direct Invocation

import MyComponent from './MyComponent';
function App() {
 return (
 <div>
 <MyComponent />
 </div>
 );
}

B. Using JSX with Props

import MyComponent from './MyComponent';
function App() {
 const myProp = "Hello, World!";
 return (
 <div>
 <MyComponent propValue={myProp} />
 </div>
 );
}

C. Conditional Rendering

import MyComponent from './MyComponent';
function App() {
 const shouldRender = true;
 return (
 <div>
 {shouldRender && <MyComponent />}
 </div>
 );
}

If you are new to React development and want to explore the language fundamentals, consider enrolling in the React JS course by upGrad.

Rendering Lists of Components

import MyComponent from './MyComponent';
function App() {
 const items = [1, 2, 3];
 return (
 <div>
 {items.map(item => <MyComponent key={item} item={item} />)}
 </div>
 );
}

These methods showcase the flexibility and simplicity of using functional components, enhancing code readability and maintainability.

Problems With Using React Functional Components

While functional components offer a simpler and more concise way to create React components, they come with their own set of challenges:

A. State and Lifecycle Management

Before the introduction of hooks, functional components were stateless, meaning managing state and lifecycle methods was limited to class components. This restriction made functional components less powerful compared to their class-based counterparts.

B. Performance Concerns

Functional components are recreated on each render, which can lead to performance issues, especially if the component performs complex calculations or has many children. Without proper memoization using React.memo or hooks like useMemo and useCallback, this can result in unnecessary re-renders and decreased performance.

C. Limited Prior to Hooks

The true potential of functional components was unlocked with the introduction of hooks in React 16.8. Before hooks, functional components were restricted in functionality and could not use state or lifecycle features, which limited their usage in complex applications.

Despite these challenges, the advent of hooks has significantly mitigated these issues, making functional components a robust choice for modern React development.

Advantages of Using Hooks in React Functional Components

Hooks have revolutionized the way functional components are used in React, bringing several advantages:

  1. State Management: Hooks like useState allow functional components to manage state, making them as powerful as class components. This simplifies the state management logic within functional components, enabling cleaner and more concise code.
  2. Side Effects: The useEffect hook provides a way to handle side effects such as data fetching, subscriptions, and DOM manipulations within functional components. It combines the functionalities of componentDidMount, componentDidUpdate, and componentWillUnmount from class components, streamlining the code.
  3. Reusability and Composition: Custom hooks enable developers to extract and reuse stateful logic across different components, promoting code reuse and separation of concerns. This modular approach helps in maintaining a cleaner and more manageable codebase.
  4. Improved Performance: Hooks like useMemo and useCallback help in optimizing performance by memoizing values and functions, preventing unnecessary re-renders. This ensures that functional components remain performant, even with complex logic.

Overall, hooks have transformed functional components into a powerful tool, making React development more intuitive and efficient.

React Arrow Function Component

Most developers prefer creating functional components using arrow functions over components with specific function keywords. Creating components using the arrow function is more accessible, and the code looks clean; anyone can easily understand the code. It also has one more advantage; Arrow functions handle this context in a lexical way, whereas normal functions do it dynamically.

Below is the example for react functional component with arrow function

import React from "react";
const Video = (props) => {
    return <h1> Video Component - {props.name}</h1>
} 
export default Video;

Still, we can pass props to the arrow functions; nothing has been changed to props. In the end, we will export this component so that we can use this later in other components.  

Below is the example for importing the Video component and using it to render the data.

import React from 'react';
import Video from "./components/Video";
import './App.css';
function App() {
  return (
    <div className="App">
      <Video />
    </div>
  );
}

export default App;

React Stateless Function Component

The goal of creating stateless functional components is to focus on the UI. Stateless functional components do not have state or lifecycle methods. It is easy to make and can easily understand by other developers. Also, we don’t have to worry about this keyword. Since we don’t have to worry about managing the state, it improved overall performance.

Below is the typical stateless functional component example, which will be used to display the list of videos. We can also show the results of videos searched by a keyword without managing the state.

import React from 'react';
let List = (props) => {
    return(
        <div>
            {
                props.videos.map((video, i)=>{
                    return(
                        <div key={i}>
                            {video.url}
                        </div>
                    );                
                })
            }
        </div>
    );
}
export default List;

The above code snippet is responsible for displaying the videos on the webpage; it does not manage any state. It takes the data from the prop and shows it on the browser. So the stateless functional components focus on the UI rather than focusing on managing the states.

React Function Component: State

With the introduction of React 16, it is possible to create a state and maintain the form inside the functional component. It is possible with the help of React Hooks; it’s a React new feature that allows us to “hook” the functionality into functional components.  

One of the essential hooks provided by React is the useState() hook, which is used to create the state and update the form. The useState() takes an object as a parameter and returns an array; we can use array destructuring to get the two essential elements from the collection: the state’s current value and a function used to update the form.

Below is the example for react functional component state

import React, {useState} from "react";
const MyComponent = () => {
    const [value, setValue] = useState(1);
    return (
        <div>
            <p>{value}</p>
            <button onClick={() => setValue((value + 1))}>Increment Value</button>
        </div>
    );
};

In the above example, we are passing 1 to the useState(), which is the initial value for the state. We will destructure the array returned by useState() and get the two elements: value and setValue(). We can use value to access the state and setValue() to update the state.

You can see how easy it is to create and update the state in functional components using the useState() hook. React Hooks enable us to use state in React Function Components using arrow functions.

React Function Component: Event Handler 

Like javascript, React also allows us to call functions and execute a piece of code when a user interacts with DOM elements. Technically, these interactions are called events; there are different types of interactions such as click, mouse, keyboard, etc.  

In React, each component has its own markup and methods. We can simply define a function inside our component, and we can call it inside the return() method.

There are two main differences in React event handling -

First, all the react events use camelCase syntax; Second, react calls the handler method inside the {} braces. Take a look at the below code snippet

<button onClick={doSomething}>Do something</button>;

If you also observe, we will not call the method like this doSomething(); instead, we will reference the method. If we call a method doSomething() like this, this method will automatically get called when the DOM renders to the browser.

Take a look at the below example, which uses the onClick event.

doSomething = e => {
  e.preventDefault();
 // TODO: Write your logic here
}
render() {
    return(
        <a onClick={this.doSomething} href="/">
      Click me
        </a>
    );
}

Now that we have seen how to handle events inside the functional components. We should always keep in mind that whenever we are using any events, it should follow the camelCase syntax and we should call the handler methods within the {} braces.

React Function Component: Callback Function

When a component re-renders, every function inside the component is recreated, and therefore these functions’ references change between renders.

React useCallback (callback, dependencies) will return a memoized instance of the callback that only changes if one of the dependencies has changed. Instead of recreating the function object on every re-render, we can use the same function object between renders.

const memoized = useCallback(() =>  
{    
    // the callback function to be memoized  
},  
    // dependencies array
[]);

Let us look at the most common usecase for useCallback()

Imaging there is the EmployeeList component that renders the list of employees.

import useSearch from './fetch-items';
function EmployeeList({ term, onItemClick }) {
    const items = useSearch(term);
    const map = item => <div onClick={onItemClick}>{item}</div>;
    return <div>{items.map(map)}</div>;
}
export default React.memo(EmployeeList);

The list could be extensive, maybe hundreds of items. To prevent useless list re-renderings, you wrap it into React.memo().

The parent component of EmployeeList provides a handler function to know when an item is clicked.

import { useCallback } from 'react';
export function Dashboard({ term }) {
    const onItemClick = useCallback(event => {
    console.log('You clicked ', event.currentTarget);
    }, [term]);
    return (
   <EmployeeList
        term={term}
        onItemClick={onItemClick}
   />
);
}

onItemClick callback is memoized by useCallback(). As long as the term is the same, useCallback() returns the same function object.

When the Dashboard component re-renders, the onItemClick function object remains the same and doesn't break the memoization of EmployeeList.

React Function Component: Lifecycle

If you have used React class-based components before, you probably used React lifecycle methods such as componentDidMount, componentDidUpdate, componentWillUnmount etc. With an introduction to the React 16, it is also possible to use the behavioral lifecycle methods inside the functional components.

1. componentDidMount

A lifecycle method runs or executes after the component is mounted and rendered to the DOM. It is called only once during the component's lifecycle after the component mounting is done.

How to use the class-based component?

import React from "react"; 
Class Component extends React.Component {
 componentDidMount() {
 console.log("Behavior before the component is added to the DOM");
 }
render() {
 return <h1>Hello World</h1>;
 }
};

How to use the function-based components?

import React, { useEffect } from "react";
const Component = () => {
    useEffect(() => {  
        console.log("Behavior before the component is added to the DOM");
    }, []);  
    // Mark [] here.
    return <h1>Hello World</h1>;
};

2. componentDidUpdate

It is also one of the lifecycle methods that execute after an update in the component and checks if a specific prop or state has updated.

How to use the class-based component?

import React from "react"; 
class Component extends React.Component {
 componentDidUpdate(prevProps) {
 if (this.props.foo !== prevProps.foo) {
 console.log("Behavior when the value of 'foo' changes.");
 }
 } 
render() {
 return <h1>Hello World</h1>;
 }
};

How to use in function based component?

import React, { useEffect } from "react"; 
const Component = ({ foo }) => {
 useEffect(() => {
 console.log("Behavior when the value of 'foo' changes.");
 }, [foo]); 
return <h1>Hello World</h1>;
};

3. componentWillUnmount

React useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners, replicating the behaviour of componentWillUnmount

How to use the class based component?

import React from "react"; 
class Component extends React.Component {
 componentWillUnmount() {
 console.log("Behavior right before the component is removed from the DOM.");
 }
render() {
 return <h1>Hello World</h1>;
 }
};

How to use in function based component?

import React, { useEffect } from "react";
const Component = () => {
 useEffect(() => {
 return () => {
 console.log("Behavior right before the component is removed from the DOM.");
 }
 }, []); 
return <h1>Hello World</h1>;
};

Pure React Function Component  

A function is pure if:

  • The return value is only determined by its input values
  • The return value is always the same for the same input values

Two Ways to Do It in React Functional Components

There are two ways to do it in React functional components:

1. Using memo from react

import React, { memo } from 'react'; 
const Component = (props) {
  return (
    // Component code
  )
} 
// Wrap component using "memo" HOC
export default memo(Component);

2. Using pure from recompose

import React from 'react';
import { pure } from 'recompose'; 
const Component = (props) {
  return (
    // Component code
  )
} 
// Wrap component using "pure" HOC
export default pure(Component);

React Function Component: Export and Import

As I said earlier, components are the building blocks of react applications. To reuse the components, first, we need to export them from the javascript file and import it into the other javascript file in which we want to use that component. Components are just the normal javascript functions; we can use these components' standard import and export statements.

Examples:

Below is the example for exporting the functional component using the export keyword-

import React from 'react'; 
const Dashboard = () => {
  return <h1>This is dashboard component</h1>;
};
 export default Dashboard;

Below is the example for importing the component using the import keyword -

import React from 'react'; 
import Dashboard from './Dashboard.js'; 
const App = () => {
  return <Dashboard />;
}; 
export default App;

Every component has at least one default export. To import the default export from a file, one can use only the path and any keyword import before it.

Below is the example for exporting the default component

export default function App() {
    return (
      <div className="App">
        <p>Hello World</p>
      </div>
    );
}

Below is the example for importing the default component 

import App from './App'; 
ReactDOM.render(
  <React.StrictMode>
    <App />
   </React.StrictMode>,
  document.getElementById('root')
);

React Function Component: Ref

Refs are a function that use to access the DOM from components. You only need to attach a ref to the element in your application to provide access to it from anywhere within your component without using props and all.

We can also use Refs to direct access to React elements and use callbacks with them.

We should only use refs when the required interaction cannot be achieved using state and props.

We can use refs to do anything that needs to be manipulated in the DOM. Some exemplary cases include focus, test selection, media playback, triggering mandatory animations, or integrating with the third-party DOM library.

Below is the syntax for the ref

const ref = useRef(null);  

Below is the example for the ref in the functional component

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

React Function Component: Proptypes

PropTypes is React’s internal mechanism for adding type checking to components. React components use a particular property named propTypes to set up type checking.  

import PropTypes from 'prop-types';
function ReactComponent({name}) {
// ...implement render logic here
} 
ReactComponent.propTypes = {
    name: PropTypes.string.isRequired,
}

React Function Component: Typescript

Typescript is a superset of javascript; it is a strictly typed language. If your react application wants that strongly typed system, you should try creating components using Typescript. If you are thinking that creating functional components in typescript needs a lot of changes, then take a look at the below code snippet  

Below is the example for designing the typescript react practical component -  

import React from 'react'; // we need this to make JSX compile

type CardProps = {
  title: string,
  paragraph: string
} 
export const Card = ({ title, paragraph }: CardProps) => <div>
  <h2>{ title }</h2>
  <p>
    { paragraph }
  </p>
</div> 
const el = <Card title="Welcome!" paragraph="To this example" />

If you observe, nothing much changes; it will check the type of incoming prop that’s it.

How to Use React Functional Components? Step-by-Step

So far, we have discussed so many examples of how effectively we can use functional components in react application. 

  • We can use react functional components to create state and maintain the state. 
  • We can use react functional components to use the lifecycle methods. 
  • We can use react functional components to handle the events. 
  • We can use react functional components to import and export the functional components. 
  • We can use react functional components to pass data from parent to child and child to parent components using callbacks. 

There are so many things we can do using react functional components. Take a look at the below code snippet, it will show you what we can do with the functional components.

A. NotesList.js

import { useEffect, useState } from "react";
import Moment from "react-moment";
import { Link } from "react-router-dom";
import NotesService from "../services/NotesService"; 
const NotesList = () => { 
    const [notes, setNotes] = useState([]);
    useEffect(() => {
        NotesService.getAll()
            .then(response => {
                console.log('printing resposne', response.data);
                setNotes(response.data);
            })
            .catch(error => {
                console.log('something went wrong', error);
            })
    }, []);
    return (           
        <div className="main-content">
            <h4>List of Notes</h4>
            <div className="notes-list mt-4">
                {
                    notes.length > 0 ? notes.map(note => (
                        <div key={note.id} className="notes-preview mt-3">
                            <Link to={`/notes/${note.id}`}>
                                <h5 className="primary-color text-capitalize">{note.title}</h5>
                                <Moment fromNow className="text-italic">{note.updatedAt}</Moment>
                            </Link>
                        </div>
                    )) : <div> No notes available</div>
                }
            </div>
        </div>         
    );
} 
export default NotesList;

B. AddNote.js

import { useEffect, useState } from "react";
import { useHistory, useParams } from "react-router";
import NotesService from "../services/NotesService"; 
const AddNote = () => {
    const[title, setTitle] = useState('');
    const[body, setBody] = useState('');
    const[category, setCategory] = useState('programming');
    const[errors, setErrors] = useState(false);
    const history = useHistory();
    const {id} = useParams();
    const saveNote = (e) => {
        e.preventDefault();
        if (!title || !body) {
            setErrors(true);
            return;
        }
        const note = {title, body, category, id};
        if (id) {
            //call the service update method
            NotesService.update(note)
                .then(response => {
                    console.log("Note updated successfully", response.data);
                    history.push("/");
                })
                .catch(error => {
                    console.log("Something went wrong", error);
                })
        } else {
            //call the service create method
            NotesService.create(note)
            .then(response => {
                console.log("Note added successfully", response.data);
                history.push("/");
            })
            .catch(error => {
                console.log('something went wroing', error);
            })
        }
    }
    useEffect(() => {
        if (id) {
            NotesService.get(id)
                .then(note => {
                    setTitle(note.data.title);
                    setBody(note.data.body);
                    setCategory(note.data.category);
                })
                .catch(error => {
                    console.log("Something went wrong", error);
                })
        }
    }, []);
    return (
        <div className="create">
            <div className="text-center">
                <h5>{id ? "Update a Note" : "Add a New Note"}</h5>
                {errors && <span style={{color: 'red', fontStyle: 'italic'}}>Please enter the mandatory fields</span>}
            </div>
            <form>
                <div className="form-group">
                    <label htmlFor="title">Note Title: <sup>*</sup></label>
                    <input  
                        type="text"  
                        className="form-control"
                        id="title"
                        value={title}
                        onChange={(e) => setTitle(e.target.value)}
                    /> 
                </div>
                <div className="form-group">
                    <label htmlFor="body">Note Description: <sup>*</sup></label>
                    <textarea  
                        id="body"
                        className="form-control"
                        value={body}
                        onChange={(e) => setBody(e.target.value)}>
                    </textarea> 
                </div>
                <div className="form-group">
                    <label htmlFor="category">Note Category:</label>
                    <select
                        id="category"
                        className="form-control"
                        value={category}
                        onChange={(e) => setCategory(e.target.value)}>
                        <option value="programming">Programming</option>
                        <option value="vacation">Vacation</option>
                        <option value="meeting">Meeting</option>
                        <option value="blogging">Blogging</option>
                    </select> 
                </div>
                <div className="text-center">
                    <button onClick={(e) => saveNote(e)}>{id ? "Update Note": "Add Note"}</button>
                </div>
            </form>
        </div>
    );
}
export default AddNote;

The above example, NotesList component will be responsible for displaying the notes on to the browser. The AddNote component is responsible for taking the input from the user using the forms and passing it to the service layer to make the remote call. We have used several hooks in the AddNote component, such as useState(), useParams(), useHistory() and useEffect(). With the help of the hooks we can do so much of things in the functional component.

Conclusion

All in all, react functional components are so promising in the near future, because with introduction to React 16, using hooks we can do so many things in react functional components. Functional components will become more prominent, since there is no compelling reason to continue using two different syntaxes. This article has shown you so many things in terms of react functional components, we covered almost every single possible approach to use the react functional components in the best possible way. I hope you enjoyed this post checking out the upGrad course React JS training.

Frequently Asked Questions (FAQs)

1. What are functional components in React?

Functional components are just javascript functions, which contains some logic to perform certain actions. These components accept the data as props and return the React element which is nothing HTML content. With introduction to the React 16, writing functional components is the standard way of creating components in modern react applications.

2. Are functional components better React?

Yes functional components are better in React, with the introduction to the React hooks, we can do so much of things in functional components, even we can use lifecycle methods inside the functional component. We can even create functional components using ES6 arrow functions.

3. Why use functional components React?

Using the react functional components, one can easily understand the code. It has several advantages, first of all, functional components are just simple javascript functions that accept the information in the form of prop and return the react element, which is HTML content. There is no need to use the render() method inside functional components.

4. How do you create a functional component of a React?

Creating the functional component is just like making the javascript functions, but it accepts the props and returns the react element. Take a look at the below code snippet

import React from 'react.' 
export default function Hello() {
    return (
        <div>
            Hello World!
        </div>
    )
}

 

 

5. What are the functional component and class component in React?

Functional component is just a simple javascript function; it accepts the data in the form of props and returns the react element. Whereas the class component will be created using the class keyword, and it extends the React. Component to make the class as a react component.

6. How do you call a functional component in React?

To call functional components first, we need to export that component using export statements to make it available. Next, we can call the components just like any other HTML elements. Check the below example for your reference.

Import React from 'react';
import Video from "./components/Video";
import './App.css'; 
function App() {
  return (
    <div className="App">
      <Video />
    </div>
  );
}
export default App;

Whereas, Video is the functional component, calling it inside the App component.

 

 

RELATED PROGRAMS