Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

React Hooks: useEffect

1. Introduction

The useEffect hook allows you to perform side effects in function components. It serves various use cases like data fetching, subscriptions, or manually changing the DOM.

2. Key Concepts

2.1 What is a Side Effect?

A side effect is any operation that interacts with the outside world from your component, such as data fetching or subscriptions.

2.2 How useEffect Works

The useEffect hook runs after the render is committed to the screen.

Note: The effect can run after every render or only when certain values change.

3. Usage

3.1 Basic Syntax


import React, { useEffect } from 'react';

const MyComponent = () => {
    useEffect(() => {
        // Your code here
        return () => {
            // Cleanup code here
        };
    }, [/* dependencies */]);

    return 
My Component
; };

3.2 Example: Fetching Data


import React, { useEffect, useState } from 'react';

const DataFetchingComponent = () => {
    const [data, setData] = useState([]);

    useEffect(() => {
        fetch('https://api.example.com/data')
            .then(response => response.json())
            .then(data => setData(data));

        return () => {
            // Cleanup if necessary
        };
    }, []);

    return (
        
{data.map(item => (
{item.name}
))}
); };

4. Best Practices

  • Always provide a cleanup function if you're subscribing to an event or a data stream.
  • Use the dependency array wisely to optimize performance.
  • Avoid using state variables directly in the dependency array unless necessary.
  • Group multiple useEffect calls if they are related.

5. FAQ

What happens if I don't provide a dependency array?

If you don't provide a dependency array, the effect will run after every render.

Can useEffect return a value?

No, useEffect should return a cleanup function, not a value.

How do I perform a cleanup in useEffect?

Return a function from your effect callback to perform cleanup.