React Functional Components: In-Depth Guide (2024)

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. If you are new to web development and looking for training with certification, you should consider checking the KnowledgeHut course Web Development courses online with a certificate.

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 training by KnowledgeHut.

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" HOCexport 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" HOCexport 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.

Looking to master Python programming? Discover the best online course for Python enthusiasts. Unlock your coding potential and become a Python pro today!

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 from KnowledgeHut. You can checkout the KnowledgeHut course React JS training KnowledgeHut.

React Functional Components: In-Depth Guide (2024)
Top Articles
How to buy XRP (XRP)
Best Affiliate Marketing Strategies | For Newbies/Noobs
Mybranch Becu
Ohio Houses With Land for Sale - 1,591 Properties
Kris Carolla Obituary
Pj Ferry Schedule
Rainfall Map Oklahoma
Youtube Combe
Hello Alice Business Credit Card Limit Hard Pull
Gina's Pizza Port Charlotte Fl
7440 Dean Martin Dr Suite 204 Directions
Ally Joann
Google Doodle Baseball 76
Robert Deshawn Swonger Net Worth
Project, Time & Expense Tracking Software for Business
Robeson County Mugshots 2022
Shiftselect Carolinas
How many days until 12 December - Calendarr
Holiday Gift Bearer In Egypt
Anotherdeadfairy
Baldur's Gate 3: Should You Obey Vlaakith?
Wood Chipper Rental Menards
Wat is een hickmann?
Busted Mugshots Paducah Ky
Mikayla Campinos: Unveiling The Truth Behind The Leaked Content
Rainfall Map Oklahoma
Alternatieven - Acteamo - WebCatalog
Ewg Eucerin
Dl.high Stakes Sweeps Download
Desales Field Hockey Schedule
Armor Crushing Weapon Crossword Clue
Clearvue Eye Care Nyc
Eaccess Kankakee
Miss America Voy Board
Autopsy, Grave Rating, and Corpse Guide in Graveyard Keeper
Microsoftlicentiespecialist.nl - Microcenter - ICT voor het MKB
Edward Walk In Clinic Plainfield Il
Craigslist Org Sf
Chris Provost Daughter Addie
D3 Boards
Dadeclerk
How to play Yahoo Fantasy Football | Yahoo Help - SLN24152
18 terrible things that happened on Friday the 13th
Sdn Fertitta 2024
Windshield Repair & Auto Glass Replacement in Texas| Safelite
Foxxequeen
National Weather Service Richmond Va
Bekkenpijn: oorzaken en symptomen van pijn in het bekken
Paperlessemployee/Dollartree
Strange World Showtimes Near Century Federal Way
Denys Davydov - Wikitia
Att Corporate Store Location
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 5793

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.