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>; }
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.
Filename: App.js
Javascript
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; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: