DEV Community

Cover image for 6 use cases of the useEffect ReactJS hook
Damian Demasi
Damian Demasi

Posted on

6 use cases of the useEffect ReactJS hook

Whenever we need to make use of side effects in our application, useEffect is the way to go. This hook doesn't present many complications, except for non-primitive data types, due to how JavaScript handles them.

According to the official documentation, effects run after every completed render, but you can choose to fire them only when certain values have changed. This hook uses an array of "dependencies": variables or states that useEffect listen to for changes. When their values change, the main body of the useEffect hook is executed.

The return statement of this hook is used to clean methods that are already running, such as timers. The first time this hook is called, its main body is the one that is going to be evaluated first. All other subsequent times the hook is called, the return statement will be evaluated first, and, after that, the hook's main body. This behaviour is especially useful for cleaning code that is already running before run it again, which enable us to prevent memory leaks.

There is an interesting behaviour with this hook when we use non-primitive JavaScript data types as dependencies (e.g., arrays, objects, functions). With primitive values, such as numbers and strings, we can define a variable from another variable, and they will be the same:

const a = 1
const b = 1
a === b
// Output: true
Enter fullscreen mode Exit fullscreen mode

But with non-primitive values, such as objects, this behaviour is not the same:

{} === {}
// Output: false
Enter fullscreen mode Exit fullscreen mode

So we need to be very careful when using objects as dependencies, because even though they may look like unaltered data, they may not be so. Instead of using objects, we may want to use their properties as dependencies:

useEffect(() => {
        // Some code that uses the properties
    }, [myObject.property1, myObject.property2