useEffect isn't inherently bad practice, but it's often overused in situations where React provides better alternatives. The main issues with useEffect are:
- Unnecessary complexity - It introduces lifecycle thinking into functional components
- Performance concerns - Can cause extra renders and computations
- Timing issues - Effects run after render, which can cause visual glitches
- Cleanup complexity - Easy to create memory leaks or stale closures
Here are common scenarios where useEffect can be avoided:
Transforming Data
Bad (with useEffect):
function UserList({ users }) {
const [sortedUsers, setSortedUsers] = useState([]);
useEffect(() => {
setSortedUsers([...users].sort((a, b) => a.name.localeCompare(b.name)));
}, [users]);
return <div>{sortedUsers.map(user => <div key={user.id}>{user.name}</div>)}</div>;
}
Good (direct calculation):
function UserList({ users }) {
const sortedUsers = [...users].sort((a, b) => a.name.localeCompare(b.name));
return <div>{sortedUsers.map(user => <div key={user.id}>{user.name}</div>)}</div>;
}
Or with useMemo for expensive calculations:
function UserList({ users }) {
const sortedUsers = useMemo(
() => [...users].sort((a, b) => a.name.localeCompare(b.name)),
[users]
);
return <div>{sortedUsers.map(user => <div key={user.id}>{user.name}</div>)}</div>;
}
Responding to User Events
Bad (with useEffect):
function Form() {
const [submitted, setSubmitted] = useState(false);
useEffect(() => {
if (submitted) {
// Send analytics
analytics.track('form_submitted');
setSubmitted(false);
}
}, [submitted]);
return (
<form onSubmit={(e) => {
e.preventDefault();
setSubmitted(true);
}}>
<button type="submit">Submit</button>
</form>
);
}
Good (in event handler):
function Form() {
const handleSubmit = (e) => {
e.preventDefault();
analytics.track('form_submitted');
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
Initializing State
Bad (with useEffect):
function Profile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
setUser(getCachedUser(userId));
}, [userId]);
return <div>{user?.name}</div>;
}
Good (direct initialization):
function Profile({ userId }) {
const [user, setUser] = useState(() => getCachedUser(userId));
return <div>{user?.name}</div>;
}
Syncing with External Systems
This is where useEffect is actually appropriate:
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <div>Chat room: {roomId}</div>;
}
Fetching Data
While useEffect works for data fetching, modern alternatives are often better:
Traditional (with useEffect):
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
async function fetchUser() {
setLoading(true);
try {
const data = await api.getUser(userId);
if (!cancelled) {
setUser(data);
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
}
fetchUser();
return () => { cancelled = true; };
}, [userId]);
if (loading) return <div>Loading...</div>;
return <div>{user?.name}</div>;
}
Better (with a data fetching library):
// Using React Query/TanStack Query
function UserProfile({ userId }) {
const { data: user, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => api.getUser(userId)
});
if (isLoading) return <div>Loading...</div>;
return <div>{user?.name}</div>;
}
Key Principles to Avoid Unnecessary useEffect:
- Calculate during render - If you can compute something from props/state, do it directly
- Handle events where they happen - Put logic in event handlers, not effects
- Initialize state properly - Use state initializer functions
- Use specialized hooks - Consider
useMemo, useCallback, or third-party hooks
- Question the need - Before adding
useEffect, ask if there's a more direct approach
useEffect should primarily be used for synchronization with external systems (subscriptions, DOM manipulation, timers) rather than for managing derived state or handling events.