React Hooks: useEffect

Simplifying DOM manipulations, Data fetching and other effects

aliciachao
2 min readJul 27, 2020

--

Use Cases

As a web developer you should be comfortable manipulating the DOM and performing other side effects now and then. With React’s useEffect hook, you can easily manage and perform side effects in function components. Examples of side effects in React include:

  • Data fetching
  • Setting up a subscription
  • Manually changing the DOM
  • Other mutations, timers, logging, etc.

How Does it Work?

useEffect accepts a function, and runs this function after every completed render. It also accepts an optional second argument, a dependency array. If a dependency array is passed in, React will know to re-run the effect only when values (state/props) inside the dependency array change. This hook also takes care of cleanup if required by the component.

Tip: If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

React Hooks were unveiled at React Conference 2018. Its major features are highlighted in the conference video below. There are several demonstrations comparing code written using class components vs. function components with hooks. They also demonstrate how useEffect compares to componentDidMount, componentDidUpdate, and componentWillUnmount separately. I highly recommend watching this video, it is a great introduction to hooks and writing cleaner concise code in React.

Example Use Cases

  1. Changing the document title:
// import React Hooks
import React, { useState, useEffect } from 'react';
const Example = () => {
// declare a [state, updateState] = set(initialValue)
const [count, setCount] = useState(0);
useEffect(() => {
// Update document title using the browser API
document.title = `You clicked ${count} times`;
});
// render component
return (
<div>
<p> You clicked {count} times </p>
<button onClick={ () => setCount(count + 1) } >
Click Me!
</button>
</div>
)
}
export default Example;

2. Fetching data from an API:

const [state, setState] = useState([]);  useEffect(() => {
fetch(API_URL) // use JavaScript's fetch method to get data from an API
.then(res => res.json()) // take the API response and turn it into JSON
.then(res => {
setState(res.results); // update the value of state with results array
});
}, []);

Resources

--

--