How useEffect works in ReactJS ?
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:
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.
Step to Run Application: Run the application using the following command from the root directory of the project.
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.