When we want to perform something after each render of component then we can use the useEffect() hook. By using this Hook, we tell React that our component needs to do something after render by passing a function. React remember the function we passed in useEffect() hook and call it later after performing the DOM updates.
By default, the useEffect hook runs after the first render and after every update. React updates the DOM by the time it runs the effects.
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.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React, { useState, useEffect } from 'react' ; function App() { const [count, setCount] = useState(0); useEffect(() => { alert(`You clicked ${count} times`) }); const handleUpdate = ()=> { setCount (count + 1) } return ( <div> <div>You have clicked {count} times</div> <button onClick={ handleUpdate} > Click me </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: Now open your browser and go to http://localhost:3000/, you will see the following output.
Explanation: As we can from the above example whenever we update the state, React re-render the component, and just after that useEffect() hook call function that we have passed.