Chuck's Academy

React Hooks

The useEffect Hook

useEffect Hook

Introduction

The useEffect Hook allows handling side effects in functional components. A side effect is any operation that affects something outside the scope of the function that is running: API requests, subscriptions, manual changes to the DOM, etc.

Basic Syntax

useEffect is invoked within the functional component and allows performing a side effect.

javascript

Example Description

In this example:

  • useEffect is called after rendering the component. In each render, document.title will be updated reflecting the number of clicks.

Cleanup in useEffect

To clean up effects (such as cancelling subscriptions or timers), useEffect can return a function.

javascript

In this example, we create a timer that increments every second. When the component unmounts or before the effect runs again, the interval will be cleaned up with clearInterval.

Effect Dependencies

You can control when effects are activated by passing a dependencies array as the second argument to useEffect.

javascript

In this example, useEffect only runs when alertCount changes, unlike running after each render.

When passing an empty array

Passing an empty array [] as the second argument makes the effect run only once, similar to componentDidMount.

javascript

Ask me anything