Day 16: The useEffect Hook in React

useEffect method hook is used for operations like fetching data from an API.

Saranjeet Singh
CSFundamental
2 min readOct 23, 2020

--

By using this Hook, you tell React that your component needs to do something after rendered the component. React will remember the function you passed and call it later after performing the DOM updates. In this effect, we set the document title, we could also perform data fetching or call some other imperative API.

In the future when we will fetch data from an API, if we are using functional-based components, we will need to use useEffect hook. Let’s see an example of how it works.

Example 1

Add the following code to App.js

as you reload the page, you will see “use effect called” on the console screen. And as many times you press the button, you will see the same message on every click. It means this function runs on every reload of DOM.

However, you may not want to call useEffect on every render or rendering of DOM. So to eliminate that, we can use this way:

Example 2

what we doing here is creating a component, one method will increment the value and other will decrement it.

If you go and check, for every increment our useEffect hook will work, and it will not work for decrement.

If we just add an array to the useEffect method, we can tell it when to use it. This is pretty easy to use and remember and will help us when we will be fetching data from the API.

This is all for this tutorial, see you in the next lesson.

You can find more tutorials about programming on my YouTube channel,Tech with Saran, https://www.youtube.com/channel/UCOHJCOprtOf4caI50lJlHSQ

--

--

Saranjeet Singh
CSFundamental

I write tutorials on Python, JavaScript, React, and Django. I write for InPlainEnglish and TheStartUp .