Back To Posts
React Hooks – A Guide to useEffect

Sanket Joshi | September 13, 2024

React Hooks – A Guide to useEffect

When React introduced Hooks, one of the most transformative ones was useEffect. This hook allows functional components to perform side effects, such as fetching data, interacting with the DOM, or cleaning up resources. Let’s dive into how useEffect works and its common use cases.

What is useEffect?

useEffect is a hook that lets you perform side effects in function components. Side effects include tasks like:

  • Fetching data from an API
  • Subscribing to a WebSocket
  • Manipulating the DOM directly

It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class-based components.

Basic Example

import { useEffect } from 'react';

function ExampleComponent() {
  useEffect(() => {
    console.log('Component mounted');

    // Cleanup function to handle unmounting
    return () => {
      console.log('Component unmounted');
    };
  }, []); // Empty dependency array ensures it runs only on mount

  return <div>Example Component</div>;
}