React hooks: useEffect cheat sheet

Anita Czapla
2 min readDec 1, 2020

If you’re new to hooks too, I am going to show you how this new feature compares to the old way of working with updating state in classes.

hooks in React

Tip from official documentation:

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

Or another way of thinking about them:

“Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”.” — React

Ok, lets dive in:

on every render

componentDidMount

componentDidUpdate(prevProps, prevState)

componentWillUnmount

If you want to learn more what are clean up cases, click here.

Additional notes on comparison dependencies

How useEffect(() => {}, [value]) knows the value has changed?

Behind the scene useEffect perform shallow comparison of your passed value and then decides to call the arrow function (first argument of useEffect).

What is a shallow comparison in React?

Shallow comparison works by checking if two values are strictly equal in case of primitive types like string, numbers, if value is an object it only compares the first level properties hence shallow.

So if you shallow compare a deep nested object it will just check the reference not the values inside that object.

React uses Object.is to compare values. Object.is behaves nearly the same as strict equal === except for NaN and +0/-0. Here is really good stackoverflow overview. Also to read more aboutObject.is , click here.

If shallow comparison for passed values fails (meaning the values are not equal) and therefore the component should update, the arrow function (first argument to useEffect) is called.

If shallow comparison for passed values passes (meaning the values are equal) and therefore the component does not need to update, the arrow function (first argument to useEffect) is not called.

Key takeaways

Why do I mention about shallow comparison?

I had an issue where I was calling my effect function on every render even when value has not changed. I have noticed the value which was passed had a nested properties where the check was always failing and my function was called each time. Rookie mistake :) but I hope this is helpful to someone :)

Thank you for reading :)

--

--

Anita Czapla

Devtrepreneur, co-founder of StudyPod app: an educational tool for those with an insatiable appetite for knowledge.