Learning about useEffect hooks

Grace Yuiko Nakano
2 min readAug 24, 2021
React and useState and useEffect Hooks

In an earlier blog post, I covered my learning of the React useState hooks and the convenience of being able to access state in a functional component. We are also able to utilize useEffect in functional components to perform “side effects” which include the ability to update and render the changes on the DOM after state change.

If we compare useEffect to lifecycle react components, they are most similar to componentDidMount, componentDidUpdate, and componentWillUnmount, except componentDidMount will just read the current value without closure. We want to see the state changes persisted on the DOM without calling multiple lifecycles to establish the updates. With useEffect, we use one hook to enact a render after every update.

Here is an example of how to useState and useEffect to seamlessly update a like on a page.

  1. First, we can use React hook, useState to initialize state and set state in our functional component. We set our initial likes to 0
export default const Like = (props) => {  const [likes, setlikes] = useState(0)  useEffect(() => {
setlikes(JSON.parse(window.localStorage.getItem('likes')));
}, []);
useEffect(() => {
window.localStorage.setItem('likes', likes);
}, [likes]);
const incrementLike = (event) => {
let newlikes = likes + 1
return setlikes(newlikes)
}
return(
<div className="like">
<img id={props.name} src={thumbsUp} onClick={incrementLike} alt="" /> Yes! </h5>
<div className="like-likes">
<p><strong>{likes}</strong> Likes!</p>
</div>
</div>
)
}

2. Next we can utilize useEffect to render and update the number of likes. In this example, we are persisting state into local storage, incrementing the number of likes.

3. The useEffect hook will run after the first render and every update.

This useEffect hook is beneficial in many ways, being able to see the updated DOM without calling a page reload to reflect the changes. When I tried to see the updated state rendered on the DOM in a class component, I called lifecycle components, componentDidUpdate to implement side effects.

--

--

Grace Yuiko Nakano

Fullstack Software Engineer | Musician | Food Lover | Coffee Addict