Tutorials Logic, IN info@tutorialslogic.com

React useEffect Hook API Calls, Cleanup, Dependencies

Why These Hooks Matter

useState and useEffect are two of the most important React hooks. useState helps components store changing values, while useEffect helps components run side effects such as data fetching, timers, subscriptions, or DOM-related work after rendering.

What Is useState?

useState adds state to function components. It returns the current value and a setter function used to update that value.

What Is useState? - JSX Example

What Is useState? - JSX Example
const [count, setCount] = useState(0)

What Is useEffect?

useEffect runs code after React renders the component. It is commonly used for data fetching, timers, subscriptions, and syncing React with the outside world.

How the Dependency Array Works

Pattern When it runs
useEffect(() => { ... }) After every render
useEffect(() => { ... }, []) Only after the first render
useEffect(() => { ... }, [value]) When the listed dependency changes

Simple useEffect Example

Simple useEffect Example - JSX Example

Simple useEffect Example - JSX Example
import { useEffect, useState } from 'react'

function Timer() {
    const [seconds, setSeconds] = useState(0)

    useEffect(() => {
        const id = setInterval(() => {
            setSeconds(current => current + 1)
        }, 1000)

        return () => clearInterval(id)
    }, [])

    return <p>Seconds: {seconds}</p>
}

Fetching Data with useEffect

Fetching Data with useEffect - JSX Example

Fetching Data with useEffect - JSX Example
import { useEffect, useState } from 'react'

function Users() {
    const [users, setUsers] = useState([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        fetch('/api/users')
            .then(response => response.json())
            .then(data => {
                setUsers(data)
                setLoading(false)
            })
    }, [])

    if (loading) return <p>Loading...</p>

    return (
        <ul>
            {users.map(user => <li key={user.id}>{user.name}</li>)}
        </ul>
    )
}

Cleanup in useEffect

Some effects create resources that must be cleaned up, such as intervals, subscriptions, or event listeners. Returning a function from useEffect lets React clean them up when the component unmounts or before the effect runs again.

When to Use useEffect

  • Fetching data after render
  • Subscribing to browser or external events
  • Starting and clearing timers
  • Synchronizing with APIs outside React

Lists And Keys Failure Cases

Mistake Why it causes bugs Better approach
Forgetting dependencies Effect may use stale values Include the values the effect depends on
Putting non-side-effect logic in useEffect Adds unnecessary complexity Keep normal calculations in render when possible
Forgetting cleanup Can create memory leaks or duplicate listeners Return a cleanup function when needed
Using one large effect for unrelated tasks Makes code harder to understand Split unrelated effects into separate hooks

Best Practices

  • Use useState for local changing values
  • Use useEffect only for real side effects
  • Keep effects focused on one responsibility
  • Clean up timers, subscriptions, and listeners
  • Be honest about dependencies instead of suppressing them

Summary

useState and useEffect are core tools in modern React. useState lets components store changing values, while useEffect lets components perform side effects after rendering. Learning when to use each one, and when not to, is a major step toward writing cleaner React applications.

Before you move on

React useEffect Hook API Calls, Cleanup, Dependencies Mastery Check

5 checks
  • It returns the current value and a setter function used to update that value.
  • useEffect runs code after React renders the component.
  • It is commonly used for data fetching, timers, subscriptions, and syncing React with the outside world.
  • Some effects create resources that must be cleaned up, such as intervals, subscriptions, or event listeners.
  • Returning a function from useEffect lets React clean them up when the component unmounts or before the effect runs again.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.