React useEffect Hook

The useEffect Hook in React enables the execution of side effects in your components. Common side effects include: data fetching, direct DOM manipulation, and setting up timers.

Tutorials dojo strip

Using useEffect

useEffect takes two arguments, with the second one being optional:

JavaScript

We’ll use a timer as an illustrative example.

Example

Using setTimeout() to count 1 second after the initial render:

JavaScript

However, this keeps counting continuously. The useEffect executes on every render. This means that when count changes, the component re-renders, triggering the effect again. This isn’t desirable. There are ways to control when side effects should run.

You should always provide the second parameter, which can take an array of dependencies.

Controlling the Execution

Example 1: No dependencies:

JavaScript

Example 2: Empty array:

JavaScript

Example 3: With dependencies (props or state values):

JavaScript

To fix our timer issue, let’s ensure the effect only runs on the initial render.

Example

Run the effect only once:

JavaScript

Example

Here is an example where the useEffect Hook depends on a variable. The effect re-runs whenever the count variable updates:

JavaScript

When there are multiple dependencies, they should all be included in the useEffect dependency array.

Cleaning Up Effects

Certain effects need to be cleaned up to prevent memory leaks. This includes timeouts, subscriptions, event listeners, and other effects that are no longer necessary.

Cleanup is done by returning a function at the end of the useEffect Hook.

Example

Clean up the timer:

JavaScript
Tutorials dojo strip