Dung (Donny) Nguyen

Senior Software Engineer

Overview of useEffect in React.js

useEffect is a React Hook that allows you to perform side effects in your functional components. Side effects are operations that interact with external systems or APIs, such as fetching data, manipulating the DOM, setting up subscriptions, or starting timers.

How useEffect Works

Syntax

useEffect(() => {
  // Your effect logic here
}, [dependencies]);

Common Use Cases

Cleanup Function

If your effect needs to clean up (for example, remove event listeners or cancel timers), return a function from your effect:

useEffect(() => {
  // Setup logic

  return () => {
    // Cleanup logic
  };
}, [dependencies]);

React will call the cleanup function before the effect runs again and when the component unmounts.

Example

import { useState, useEffect } from "react";

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);
}

In this example, the document title updates every time count changes.

Key Points

In summary: useEffect is a powerful and essential hook for managing side effects and component lifecycle events in React functional components.