- Blog Categories
- Project Management
- Agile Management
- IT Service Management
- Cloud Computing
- Business Management
- Business Intelligence
- Quality Engineer
- Cyber Security
- Career
- Big Data
- Programming
- Most Popular Blogs
- PMP Exam Schedule for 2024: Check PMP Exam Date
- Top 60+ PMP Exam Questions and Answers for 2024
- PMP Cheat Sheet and PMP Formulas To Use in 2024
- What is PMP Process? A Complete List of 49 Processes of PMP
- Top 15+ Project Management Case Studies with Examples 2024
- Top Picks by Authors
- Top 170 Project Management Research Topics
- What is Effective Communication: Definition
- How to Create a Project Plan in Excel in 2024?
- PMP Certification Exam Eligibility in 2024 [A Complete Checklist]
- PMP Certification Fees - All Aspects of PMP Certification Fee
- Most Popular Blogs
- CSM vs PSM: Which Certification to Choose in 2024?
- How Much Does Scrum Master Certification Cost in 2024?
- CSPO vs PSPO Certification: What to Choose in 2024?
- 8 Best Scrum Master Certifications to Pursue in 2024
- Safe Agilist Exam: A Complete Study Guide 2024
- Top Picks by Authors
- SAFe vs Agile: Difference Between Scaled Agile and Agile
- Top 21 Scrum Best Practices for Efficient Agile Workflow
- 30 User Story Examples and Templates to Use in 2024
- State of Agile: Things You Need to Know
- Top 24 Career Benefits of a Certifed Scrum Master
- Most Popular Blogs
- ITIL Certification Cost in 2024 [Exam Fee & Other Expenses]
- Top 17 Required Skills for System Administrator in 2024
- How Effective Is Itil Certification for a Job Switch?
- IT Service Management (ITSM) Role and Responsibilities
- Top 25 Service Based Companies in India in 2024
- Top Picks by Authors
- What is Escalation Matrix & How Does It Work? [Types, Process]
- ITIL Service Operation: Phases, Functions, Best Practices
- 10 Best Facility Management Software in 2024
- What is Service Request Management in ITIL? Example, Steps, Tips
- An Introduction To ITIL® Exam
- Most Popular Blogs
- A Complete AWS Cheat Sheet: Important Topics Covered
- Top AWS Solution Architect Projects in 2024
- 15 Best Azure Certifications 2024: Which one to Choose?
- Top 22 Cloud Computing Project Ideas in 2024 [Source Code]
- How to Become an Azure Data Engineer? 2024 Roadmap
- Top Picks by Authors
- Top 40 IoT Project Ideas and Topics in 2024 [Source Code]
- The Future of AWS: Top Trends & Predictions in 2024
- AWS Solutions Architect vs AWS Developer [Key Differences]
- Top 20 Azure Data Engineering Projects in 2024 [Source Code]
- 25 Best Cloud Computing Tools in 2024
- Most Popular Blogs
- Company Analysis Report: Examples, Templates, Components
- 400 Trending Business Management Research Topics
- Business Analysis Body of Knowledge (BABOK): Guide
- ECBA Certification: Is it Worth it?
- How to Become Business Analyst in 2024? Step-by-Step
- Top Picks by Authors
- Top 20 Business Analytics Project in 2024 [With Source Code]
- ECBA Certification Cost Across Countries
- Top 9 Free Business Requirements Document (BRD) Templates
- Business Analyst Job Description in 2024 [Key Responsibility]
- Business Analysis Framework: Elements, Process, Techniques
- Most Popular Blogs
- Best Career options after BA [2024]
- Top Career Options after BCom to Know in 2024
- Top 10 Power Bi Books of 2024 [Beginners to Experienced]
- Power BI Skills in Demand: How to Stand Out in the Job Market
- Top 15 Power BI Project Ideas
- Top Picks by Authors
- 10 Limitations of Power BI: You Must Know in 2024
- Top 45 Career Options After BBA in 2024 [With Salary]
- Top Power BI Dashboard Templates of 2024
- What is Power BI Used For - Practical Applications Of Power BI
- SSRS Vs Power BI - What are the Key Differences?
- Most Popular Blogs
- Data Collection Plan For Six Sigma: How to Create One?
- Quality Engineer Resume for 2024 [Examples + Tips]
- 20 Best Quality Management Certifications That Pay Well in 2024
- Six Sigma in Operations Management [A Brief Introduction]
- Top Picks by Authors
- Six Sigma Green Belt vs PMP: What's the Difference
- Quality Management: Definition, Importance, Components
- Adding Green Belt Certifications to Your Resume
- Six Sigma Green Belt in Healthcare: Concepts, Benefits and Examples
- Most Popular Blogs
- Latest CISSP Exam Dumps of 2024 [Free CISSP Dumps]
- CISSP vs Security+ Certifications: Which is Best in 2024?
- Best CISSP Study Guides for 2024 + CISSP Study Plan
- How to Become an Ethical Hacker in 2024?
- Top Picks by Authors
- CISSP vs Master's Degree: Which One to Choose in 2024?
- CISSP Endorsement Process: Requirements & Example
- OSCP vs CISSP | Top Cybersecurity Certifications
- How to Pass the CISSP Exam on Your 1st Attempt in 2024?
- Most Popular Blogs
- Best Career options after BA [2024]
- Top Picks by Authors
- Top Career Options & Courses After 12th Commerce in 2024
- Recommended Blogs
- 30 Best Answers for Your 'Reason for Job Change' in 2024
- Recommended Blogs
- Time Management Skills: How it Affects your Career
- Most Popular Blogs
- Top 28 Big Data Companies to Know in 2024
- Top Picks by Authors
- Top Big Data Tools You Need to Know in 2024
- Most Popular Blogs
- Web Development Using PHP And MySQL
- Top Picks by Authors
- Top 30 Software Engineering Projects in 2024 [Source Code]
- More
- Tutorials
- Practise Tests
- Interview Questions
- Free Courses
- Agile & PMP Practice Tests
- Agile Testing
- Agile Scrum Practice Exam
- CAPM Practice Test
- PRINCE2 Foundation Exam
- PMP Practice Exam
- Cloud Related Practice Test
- Azure Infrastructure Solutions
- AWS Solutions Architect
- AWS Developer Associate
- IT Related Pratice Test
- ITIL Practice Test
- Devops Practice Test
- TOGAF® Practice Test
- Other Practice Test
- Oracle Primavera P6 V8
- MS Project Practice Test
- Project Management & Agile
- Project Management Interview Questions
- Release Train Engineer Interview Questions
- Agile Coach Interview Questions
- Scrum Interview Questions
- IT Project Manager Interview Questions
- Cloud & Data
- Azure Databricks Interview Questions
- AWS architect Interview Questions
- Cloud Computing Interview Questions
- AWS Interview Questions
- Kubernetes Interview Questions
- Web Development
- CSS3 Free Course with Certificates
- Basics of Spring Core and MVC
- Javascript Free Course with Certificate
- React Free Course with Certificate
- Node JS Free Certification Course
- Data Science
- Python Machine Learning Course
- Python for Data Science Free Course
- NLP Free Course with Certificate
- Data Analysis Using SQL
- Free Courses
React Functional Components with Examples [In-Depth Guide]
Updated on 28 October, 2024
32.89K+ 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