Skip to content
Related Articles
Open in App
Not now

Related Articles

How to call loading function with React useEffect?

Improve Article
Save Article
Like Article
  • Last Updated : 05 Jan, 2021
Improve Article
Save Article
Like Article

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.


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

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Project Structure

Filename: 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(() => {
  }, [])
  return (
    <div style={{ margin: 200 }}>
      <button onClick={() => updatebtnText("Hi")} >
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start


After clicking button, the text changes

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!