Clean Code Hack: A Short Guide to useEffect Usage in React

A few weeks ago, while assisting a friend, a junior developer at a small company, I encountered a notably disorganised codebase. The experience illuminated a common issue many developers face. Particularly alarming was the state of their components—massive, overburdened, and straying far from component-first design principles.

However, my focus shifted to a recurring element: the useEffect hook.

In React development, useEffect is a powerful tool that, when used effectively, can significantly enhance a component's functionality. The following examples are reflective of a common pattern I have observed in many codebases:

A common pattern for useEffect usage

While this approach is valid and serves its intended purpose, it raises questions about readability and maintainability.

Pivoting to another example, let's delve into a scenario from a recent code review of mine that further illuminates this common pattern:

A recent code review

Essentially, the code above is the same as:

useEffect code from a recent code review

This snippet, though operational, does not immediately convey its intent, underscoring the need for a more structured approach to employing useEffect.

What I propose involves encapsulating the hook and its logic within a named function, accompanied by explanatory comments, for example:

useCheckKeyIsCompleted function

This approach doesn’t just make clear what the code is meant to do; it also illuminates the specific situations in which the code will run. It helps anyone reading the code to quickly grasp when the useEffect will come into play and the kind of tasks it is handling, whether that’s responding to a user’s action, fetching data when a component loads, or any other event that might prompt a change in the component.

A seasoned developer once advised me that comments should elucidate the ‘Why’ rather than the ‘How.’ By adopting this methodology, the functionality becomes transparent, promoting reusability and simplifying the integration of similar logic in various parts of an application.

Incorporating this refined approach to useEffect can significantly enhance the readability and maintainability of your code, making it a beneficial practice for developers to adopt in their toolkit.

Regresar al blog

Deja un comentario