Open In App

How To Call Loading Function With React useEffect?

Last Updated : 07 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The useEffect runs by default after every render of the component. When placing useEffect in our component we tell React that we want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates. 

If we pass only a callback, the callback will run after each render. If we just want to run the useEffect function after the initial render, as a second argument, we can give it an empty array. If we pass a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. 

For example, the callback will run after the first render and after any render that one of varOne or varTwo is changed for the following code:

useEffect(() => console.log('Hi '), [varOne, varTwo])

If we pass the second argument an empty array after each render’s React will compare the array and will see nothing was changed and callback will be called only after the first render.

Syntax:

const MyComponent = (props) {
    useEffect(() => {
        loadDataOnlyOnce();
    }, []);
    return <div> {/* jsx code */} </div>;
}

Steps To Call Loading Function With React useEffect

Step 1: Create a React application using the following command

npx create-react-app foldername

Step 2: Move to the project directory using the following command

cd foldername

Project Structure

Project Structure

Example

This React component initializes a btnText state using useState. The useEffect hook runs once when the component mounts, calling the loadDataOnlyOnce function to update the button text to “Hello kapil”. The button click event allows updating the btnText to “Hi” when clicked.

JavaScript
//App.js

import React, { useEffect, useState } from "react";

const App = (props) => {
    const [btnText, updatebtnText] = useState("")

    const loadDataOnlyOnce = () => {
        updatebtnText("Hello kapil")
    }

    // This function will called only once
    useEffect(() => {
        loadDataOnlyOnce();
    }, [])

    return (
        <div style={{ margin: 200 }}>
            <button onClick={() => updatebtnText("Hi")} >
                {btnText}
            </button>
        </div>
    );
}

export default App;


Run the application using the following command.

npm start

Output

After clicking button, the text changes



Next Article

Similar Reads