Code Tips #1

Code Tips #1

Hi everyone,

I was recently working on a project and I noticed two code tips that could help you improve your code efficiency and readability.


Tip #1: Using useCallback instead of useRef for DOM Element Tracking

The first tip involves tracking the width of a DOM element. Many developers often use useRef with useEffect to manage this task, like in the code below:

While this works, there is a cleaner and more efficient approach: using a useCallback ref instead.

By using useCallback, you can immediately access the DOM node without needing an additional useEffect, making the code more reactive and concise. This approach eliminates the need for side effects, resulting in simpler and more maintainable code.


Tip #2: Refactoring switch Statements for Conditional Rendering

The second tip is about managing multiple conditions in your React component. A switch statement is a common choice when rendering different UI elements based on some state:

However, you can make this logic more concise and readable by using an object lookup, as shown below:

With the object lookup approach, your code becomes more scalable and easier to maintain, especially as the number of cases grows. This structure also avoids potential issues with code duplication and makes adding new conditions faster and simpler.

By adopting these two approaches, you can make your code cleaner, more reactive, and easier to maintain.

Let me know what you think or if you have any other tips to share!

#React #JavaScript #WebDevelopment #CleanCode #FrontEnd #CodingTips #ReactBestPractices

Eduardo Lopes Ferreira

Senior Full Stack Mobile-Focused Engineer | React Native | Flutter | Node

2mo

Very informative!

Like
Reply
Ericlefyson Silva

Senior Software Engineer | Front-End developer | Mobile Engineer | React | Next.js | TypeScript | Flutter

2mo

Very informative

Like
Reply
Fernando Nunes

Software Engineer | Full Stack Developer | Angular | Nodejs | Nestjs | React | AWS | Azure

2mo

Great tip !

Like
Reply
Vitor Raposo

Data Engineer | Python | SQL | Azure Cloud | Azure Databricks | AWS Cloud | AWS Glue

2mo

Great tips! Small changes like using useCallback and object lookups can make a big difference in React code maintainability.

Like
Reply

To view or add a comment, sign in

More articles by Antonio Fulgêncio

Insights from the community

Others also viewed

Explore topics