Middle
Should I use useEffect or try to avoid it?
sobes.tech AI
Answer from AI
useEffect is the main hook in React for managing side effects such as data fetching, subscriptions, or DOM manipulations. Its use is justified and necessary when you need to run code after rendering or when dependencies change.
However, avoid excessive or incorrect use of useEffect, for example, when pure computations or other hooks (useMemo, useCallback) can suffice. Completely removing useEffect is not recommended, but it's important to write effects carefully, monitor dependencies, and avoid infinite loops.
An example of correct use of useEffect for data loading:
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => setUser(data));
}, [userId]); // effect triggers when userId changes
if (!user) return <div>Loading...</div>;
return <div>{user.name}</div>;
}
In summary: useEffect is a useful tool, but it should be used consciously and not abused.