Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

React useEffect Hook API Calls, Cleanup, Dependencies: Tutorial, Examples, FAQs & Interview Tips

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.

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

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

Simple useEffect 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

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

Common Mistakes

MistakeWhy it causes bugsBetter approach
Forgetting dependenciesEffect may use stale valuesInclude the values the effect depends on
Putting non-side-effect logic in useEffectAdds unnecessary complexityKeep normal calculations in render when possible
Forgetting cleanupCan create memory leaks or duplicate listenersReturn a cleanup function when needed
Using one large effect for unrelated tasksMakes code harder to understandSplit 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.

Key Takeaways
  • useState stores changing local values inside a function component.
  • useEffect runs side-effect logic after rendering.
  • Dependency arrays control when an effect should run.
  • Cleanup functions are important for timers, listeners, and subscriptions.
  • Not every piece of logic belongs in useEffect; use it only for real side effects.

Ready to Level Up Your Skills?

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