For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentReact Functional Components with Examples [In-Depth Guide]

React Functional Components with Examples [In-Depth Guide]

Published
23rd Apr, 2024
Views
view count loader
Read it in
19 Mins
In this article
    React Functional Components with Examples [In-Depth Guide]

    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).

    If you are new to React development and want to explore the language fundamentals, consider enrolling in the React js training by KnowledgeHut.  

    What are React Components?

    As discussed above, react components are the core building blocks of any react application. It is reusable and works independently. The goal of the react component is to divide the complete view into smaller pieces. Each react component defines the idea and business logic for that view.

    There are two types of react components: class-based and Functional-based components. Class-based components are “Stateful,” whereas Functional based components are “Stateless.”

    Example of React Components

    Below is an example of a class-based component

    import React, { Component } from 'react'
    export default class Hello extends Component {
        render() {
            return(
                <div>
                Hello World!
                </div>
            )
        }
    }

    Below is an example of a functional-based component

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

    With an introduction to the React 16, functional components will do all the class-based components’ jobs using React hooks. React hooks make react development easier and faster. We can also implement React state and lifecycle methods without writing classes.  

    React Functional Components: An Introduction

    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.

    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.

    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?

    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.  

    Frequently Asked Questions (FAQs)

    1What 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.

    2Are 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.

    3Why 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.

    4How 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>
        )
    }
    5What 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.

    6How 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.

    Profile

    Bushan Sirgur

    Author

    Bushan is a dedicated, passionate, and accomplished Full Stack Developer with 5+ years of progressive experience working as a Software Engineer for an IT company in Banglore and growing his educational Youtube Channel that helps others to learn programs and other technologies. He has acquired a wide depth of knowledge and expertise in using my technical skills in programming, computer science, and software development to help organizations increase productivity, and accelerate business performance. My primary skill set includes Java/J2EE, Spring Boot, Angular, MySQL, and UI design. People like working with him because he can explain technology to everyone, from staff to executives who need him to tie together the details and the big picture.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon