React Hooks Pitfalls and Best Practices/Move non-reactive logic out of effects

Keep effects focused on synchronization.

Section: Effect Dependency Pitfalls

Move non-reactive logic out of effects

tsx
tsx
useEffect(() => {
  subscribe(userId);
  return () => unsubscribe(userId);
}, [userId]);
Explanation

Effects are easier to reason about when they do only synchronization and cleanup.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Effect Dependency Pitfalls
Stale closure pitfall
Effects and callbacks capture values from the render where they were created.
OpenIn sheettsxsame section
Memoize objects used in dependencies
Avoid recreating dependency objects every render when identity matters.
OpenIn sheettsxsame section
Perform event-specific work in event handlers
Do not move user-triggered logic into effects unnecessarily.
OpenIn sheettsx4 tag match
Derive data during render when possible
Avoid effects that only derive data from props/state.
OpenIn sheettsx3 tag match
Call hooks only at the top level
Do not call hooks in conditions, loops, or nested functions.
OpenIn sheettsx2 tag match
Do not memoize everything
Memoization has a cost; use it when it solves a concrete problem.
OpenIn sheettsx2 tag match