Give me a few example practical uses of useEffect in React.
- User
Give me a few example practical uses of useEffect in React.
Assistant
In React, useEffect is a hook that lets you perform side effects in function components. Here are some practical uses:
- Fetching data from an API when a component mounts
- Setting up and cleaning up subscriptions or event listeners
- Updating the document title based on component state
- Syncing a component with an external system like localStorage
Here's an example of fetching data:
function UserProfile({ userId }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchUser() { setLoading(true); try { const response = await fetch(`/api/users/${userId}`); const data = await response.json(); setUser(data); } catch (error) { console.error("Failed to fetch user:", error); } finally { setLoading(false); } } fetchUser(); }, [userId]); // Re-run when userId changes if (loading) return <p>Loading...</p>; if (!user) return <p>User not found</p>; return <div>{user.name}</div>; }Would you like me to explain or break down this code?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.