ReactJS: “useEffect” Hook Explained

In React 16.8, Hooks were introduced to functional components to allow them to maintain state and other React features. Functional components can now utilize the logic previously restricted to class components making them very dynamic. Since their introduction, Hooks have become widely adopted as they leverage more control, with less code. If you want to dive into a detailed overview on Hooks see here. In this article I will be going over one of the React hooks that I have recently been experimenting with: useEffect.

useEffect

Reminder when using hooks do not forget to import them as seen on line 1. Let’s dissect what this component is doing. As you can see we are implementing the useState hook that allows us to use and set state but don’t worry about that for now. I am rendering an h1 with my state of “name” included, and I have a button that will change that name to “Dough” when clicked. Let’s look at what our useEffect hook is doing here. useEffect will fire on every update including renders, so when our component first renders it is going to set the title of the document to our state which is “Lucas”. Once I hit the button to change the name the useEffect will fire again and set the title to our state which now reads “Doug”.

Working with the Dependency Array

Here, I have added LastName to state and another button that will change the last name to “Looperman” on click. In my useEffect I have the title set to first name + last name. So you would think that the document title would change when the the lastName state changes, but with the dependency array [name], the effect is told to depend on specifically that piece of state changing. You can also pass in an empty array which will tell the effect to only run once immediately after the original render.

I hope this gave anyone trying to learn hooks a brief understanding of useEffect. There is still more to learn so be sure to check out the documentation linked in the intro. I would also recommend copying this code into a react app and playing around with it to get a better understanding and to see useEffect in action :)

Cheers

useEffect(() => {document.title = `${name}`})return (<div><h1>{name} is using this application </h1><button onClick ={()=> setName("Doug")}>Change name</button></div>)

Before useEffect, componentDidMount functions would be full of unrelated logic all in one function. There might be a fetch request at the beginning and later you might be manipulating the DOM by changing the title of the page. The useEffect hook will fire after every update(including render) allowing you to be able to break up that componentDidMount into clearer and simpler functions. Let’s look at useEffect in a basic example.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store