DEV Community

amdiamond107
amdiamond107

Posted on

The Power and Intricacies of useEffect Hooks in React.js

If you google search the term "side effect" the first result you'll likely see within your browser will read something like the sentence below...

"a secondary, typically undesirable effect of a drug or medical treatment."

In the context of React.js (and computer science in general), however, the term holds an entirely different meaning, as summarized below...

In computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment. Examples of side effects include, but are not limited to:

  • Modifying a non-local variable
  • Modifying a static local variable
  • Modifying a mutable argument passed by reference
  • Performing I/O or calling other functions with side-effects

In the presence of side effects, a program's behavior may depend on history, meaning that the order of evaluation matters.

Side effects play an important role in the design and analysis of programming languages. The degree to which side effects are used depends on the programming paradigm. For example, imperative programming is commonly used to produce side effects, to update a system's state. By contrast, declarative programming is commonly used to report on the state of system, without side effects.

In React.js, we leverage imperative programming principles, such as useEffect hooks, which, in turn, allow us to incorporate desirable side effects, like data manipulation from one webpage to another within our apps.

To use the useEffect hook, we must first import it, as follows:

*import React, { useEffect } from "react";
*

Then, inside our component, we call useEffect and pass in a callback function to run as a side effect:

**function App() {
useEffect(
// side effect function
() => {
console.log("useEffect called");
}
);

console.log("Component rendering");

return (


Click Me

;
)
}
**

If you run this example code, you'll see the console messages appear in this order:

Component rendering
useEffect called

So we are now able to run some extra code as a side effect any time our component is rendered.

We need to be careful, though, when implementing useEffect hooks, because when we don't incorporate any dependencies within our useEffect hook code, the useEffect can spiral out of control and run on every render.

In other words, when the count changes, a render happens, which then triggers another effect.

This is not what we typically want when leveraging useEffect hooks, but there are several measures of control, which we refer to as dependencies.

Below are examples of different scenarios involving (or not involving) dependencies within a useEffect hook...

Image description

Image description

Image description

Image description

Resources:
w3schools.com
dmitripavlutin.com

Top comments (0)