Naming useEffect Functions for Better Code

We started naming our useEffect functions some time ago. Tiny change. Outsized impact. ❌ The "Mystery" Way useEffect(() => { fetch(`/api/users/${userId}`) .then(res => res.json()) .then(setUser); }, [userId]); Four effects like this in a component? You're reading every line just to understand what's happening. ✅ The "Self-Documenting" Way useEffect(function fetchUserProfile() { fetch(`/api/users/${userId}`) .then(res => res.json()) .then(setUser); }, [userId]); Now the name tells the story. You only open it when something breaks. But the real wins were unexpected: → If you can't name it without "and" — split it. "fetchUserAndLoadPermissions" is two effects in a trench coat. → Vague names expose effects that shouldn't exist. "updateStateBasedOnOtherState" isn't an effect. It's derived state. Move it out. → Stack traces go from useless to useful. "at (anonymous)" → no idea. "at fetchUserProfile" → straight to the bug. Want to enforce it across your team? "prefer-arrow-callback": ["error", { "allowNamedFunctions": true }] Zero new libraries. Zero new patterns. Just a name. So, start naming your effects. #React #JavaScript #FrontendDevelopment #WebDev

  • No alternative text description for this image

Thoughts on this? function fetchUser() { // logic } useEffect(()=>{ fetchUser(); },[]) can this be considered self explanatory?

Another thing you can do to make it easier to understand the purpose of each useEffect is to extract logic into custom hooks, and optionally enforce guidelines (e.g., via ESLint) to limit useEffect usage in components.

Why not having a Service-File that centralized API-Calls - which then automatically exports named functions that can be included into your components. This way - in case Typescript is used - types can be defined one-time and all consuming components don't have to guess what fetch provides.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories