UseEffect — A Side Note to the Official Doc

E.Y.
2 min readMay 30, 2020

--

The following can be used as a side reference to the official React Doc:

Photo by NASA on Unsplash

useEffect

If you used lifecycle methods in Class components before to manage side effects, then useEffect Hook is just ascomponentDidMount, componentDidUpdate, and componentWillUnmount combined — so how clean the tidy the useEffect is comparing to using 3 other methods?

One classic usage is to call to an API in useEffect:

const [characters, setCharacters] = useState(dummyData);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
React.useEffect(() => {
setLoading(true);
setCharacters([]); /*clear out last data*/
setError(null);
fetch(endpoint + ‘/characters’)
.then(res => res.json())
.then(res => {
setLoading(false);
setCharacters(res.characters);
})
.catch(err => {
setLoading(false);
setError(error);
});
//[] });

Notice the highlighted commented out[] on the line above? If we don’t include it, then useEffect will run everytime in re-render s— that can be expensive. Good thing is, you can also skip effect by passing an array as an optional second argument.

useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

Or if it’s an empty array, it will only run after initial mount:

function App() {
const [isOn, setIsOn] = useState(false);
useEffect(() => {
const interval = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(interval);
}, []);
}

For some effects (like a subscription), you may also want to clean up. This is just like when you call componentWillUnmount and how you do it is to return a function in the end.

import React, { useState, useEffect } from 'react';function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {setIsOnline(status.isOnline);}
ChatAPI.subscribeToFriendStatus(props.friend.id,handleStatusChange);
// Specify how to clean up after this effect:

return function cleanup() { ChatAPI.unsubscribeFromFriendStatus(props.friend.id,handleStatusChange); };
});
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}

Note that we can have multiple useEffect hooks and when React renders our component, it will remember the effects we used, and then run our effect safter updating the DOM.

--

--

No responses yet