This Week in Coding: React useEffect

Jake Lira
2 min readMar 13, 2021

Last time we touched on React Hooks we looked at using the State Hook. This week let’s take a look at using the Effect Hook. As we know, data fetching and manually changing the DOM in React components are examples of “side effects.” The useEffect Hook is combining the componentDidMount, componentDidUpdate and componetWillUnmount together. By default useEffect will run after the first render and after every update. Let’s dive into some code. Below I have a function component with a variable for resource set to albums. It has two buttons; one for albums and another for photos.

Now when we set up our useEffect we are going to pass it a function and a second parameter. In this case the second parameter will be an array containing “resource.” This will run every time resource has been changed. If we wanted it to run similar to componentDidMount we would pass an empty array.

Every time our resource is changed useEffect should run and console log “Resource Changed.” For the scope of this blog we will be looking at using useEffect when data fetching. I will be fetching data from JSONPlaceholder.typicode.com. I will add my fetch inside useEffect and I will also add another variable called item which in this case is either the album or photo title.

Once the resource is changed by clicking the buttons the state is changed and re rendered. This is just a basic use of useEffect you can find out more here:https://reactjs.org/docs/hooks-effect.html

--

--