React useEffect

12 min read

What is React useEffect?

In this lesson, we explore React useEffect. This is an important concept in React development that you will use frequently when building real-world projects. Understanding React useEffect will help you write cleaner, more efficient code.

Syntax & Usage

The syntax and usage patterns for React useEffect follow standard React conventions. Below you will see code examples that demonstrate the most common use cases. Try modifying these examples in your own editor to experiment with different approaches.

Example

Here is a practical example demonstrating React useEffect:

Tips & Best Practices

  • Practice regularly to build muscle memory
  • Read official documentation for the most accurate information
  • Build real projects to solidify your understanding
  • Use version control to track your progress

Summary

In this lesson you learned about React useEffect. Practice writing code to reinforce these concepts and move on to the next lesson when you feel comfortable.

Examples

Example
javascript
import { useState, useEffect } from 'react';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(data => {
        setUser(data);
        setLoading(false);
      });

    return () => console.log('Cleanup!');
  }, [userId]);

  if (loading) return <p>Loading...</p>;
  return <h1>{user.name}</h1>;
}

Related articles