React Hooks useState & useEffect

May 29, 2025 1,677 views 1 min read
Beginner Tutorial
Tutorial Navigation

React Hooks: useState & useEffect

Hooks allow you to use state and other React features in functional components:

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

function UserProfile({ userId }) {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    
    useEffect(() => {
        async function fetchUser() {
            try {
                const response = await fetch(`/api/users/${userId}`);
                const userData = await response.json();
                setUser(userData);
            } catch (error) {
                console.error('Error fetching user:', error);
            } finally {
                setLoading(false);
            }
        }
        
        fetchUser();
    }, [userId]);
    
    if (loading) return <div>Loading...</div>;
    
    return (
        <div>
            <h2>{user?.name}</h2>
            <p>{user?.email}</p>
        </div>
    );
}

Hook Rules:

  • Only call hooks at the top level
  • Only call hooks from React functions
  • Use dependency arrays with useEffect
  • Clean up side effects when needed
Try It Yourself

Practice what you've learned with our interactive code editor. Modify the code and see the results instantly!