Skip to content

useEffect

vinibiavatti1 edited this page Sep 28, 2026 · 3 revisions

Synchronizes a component with an external system (e.g., browser APIs, networks, timers). It runs asynchronously after the component has rendered to the screen.

Runs On Every Render

Runs on every single render when the dependency array is completely omitted.

import { useEffect } from 'react';

export const MyComponent = () => {
    useEffect(() => {
        console.log('Component rendered or updated');
    });

    // ...
};

Runs On Mount (Only Once)

Runs only once when the component first mounts to the DOM by passing an empty dependency array.

import { useEffect } from 'react';

export const MyComponent = () => {
    useEffect(() => {
        fetch('/api').then(...);
    }, []);

    // ...
};

Runs On Mount And When Dependencies Change

Runs on mount and re-runs whenever any value inside the dependency array changes.

import { useEffect } from 'react';

export const MyComponent = () => {
    useEffect(() => {
        fetch('/api').then(...);
    }, [dep1, dep2, ...]);

    // ...
};

Cleanup Function

Cleans up side effects (like sockets, timers, or subscriptions) by returning a cleanup function from the setup callback.

import { useEffect } from 'react';

export const MyComponent = () => {
    useEffect(() => {
        const socket = ...
        return () => socket.close();
    }, []);

    // ...
};

This table maps traditional Class Component lifecycle methods to their modern Functional Component equivalents using useEffect (and React.memo for update checks).

Class Component Functional Component
componentDidMount useEffect(() => { ... }, [])
componentDidUpdate useEffect(() => { ... }, [dep1, dep2, ...])
componentWillUnmount useEffect(() => { return () => { ... } }, [])
shouldComponentUpdate React.memo(Component, arePropsEqual)

Clone this wiki locally