- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
React Functional Components with Examples [In-Depth Guide]
Updated on 28 October, 2024
32.94K+ views
• 19 min read
Table of Contents
- What is React Functional Components?
- Ways to Call the React Functional Component
- Rendering Lists of Components
- Problems With Using React Functional Components
- Advantages of Using Hooks in React Functional Components
- React Arrow Function Component
- React Stateless Function Component
- React Function Component: State
- React Function Component: Event Handler
- React Function Component: Callback Function
- React Function Component: Lifecycle
- Two Ways to Do It in React Functional Components
- React Function Component: Export and Import
- React Function Component: Ref
- React Function Component: Proptypes
- React Function Component: Typescript
- How to Use React Functional Components? Step-by-Step
- Conclusion
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:
- 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.
- 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.
- 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.
- 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