linkedin
Bad ReactJs Practices You Should Avoid

Several articles and blogs contain useful information on doing things correctly.

 

Clean code style, best practices, design patterns, and proper usage of state are all things to consider. 

 

coding2

 

Due to this, I've decided to reverse things and see what I can avoid doing.

 

In this article, we will expose the bad practices and make them interesting to read. 

 

Overusing State

 

UseState or useReducer can be useful for creating ReactJS states, but don't place everything within them.

 

The majority of new developers have difficulty with this concept.

 

They don't know when to place something in a state and when they shouldn't. 

 

The state could be used for storing data that should have been derived from the state.

 

Consider a webshop in which a full shopping basket represents a state. 

 

Having the total price set in the state as well would be a bad practice since you can already calculate it from the state. 

 

In general, it is advised to store as little data in your state as possible.

 

Simple computational tasks or variables exist for exactly that reason. 

 

Consider whether the data you need can be obtained from other variables or states before adding data to the state.

 

Using Redux When It Is Not Necessary

 

 

This is an eternal debate among React developers, so I had to include it here. 

 

It is not uncommon to hear developers wondering "Should I use Redux or Context?", "Just use Context instead of Redux" or "Is Context a good alternative to Redux?"

 

The functionality of Redux can be partially achieved by many tools and mechanisms.

 

In summary, we can understand the points made above.

 

Let's resolve this issue once and for all.

 

Context & Redux

 

Context is often thought of as a state management system by developers.

 

This isn't true! Context is a mechanism for injecting dependencies. 

 

There's no limit to what you can put inside.

 

If implemented in that way, it can be used as a state management system. 

 

To manage state within it, you use either the useState or useReducer hooks.

 

This way, you control where the state is stored, how it is updated, and where it is used.

 

Using Context is the only way to fix this issue without going through many layers of components. Try it if you only need to deal with this issue.

 

Caching & Redux

 

The majority of software applications need some type of cache to remember server data.

 

If you stick with the REST APIs, there are a number of libraries that will take care of your caching.

 

GraphQL and Apollo Client make caching really easy with React Query and Vercel's Swr.

 

If we use a more modern approach, we can use React Query or SWR Vercel.

 

At that point, you do not need Redux in your app if caching is the only functionality you need. 

 

What’s the purpose of using Redux?

 

The Redux application is a generic state management tool.

 

It can be used in many different ways. 

 

Caching state, UI state, complex data management on the client, middlewares, etc. are some of the more noticeable ones.

 

Usually, you will only need to use partial Redux features depending on what the application is trying to accomplish.

 

Component declaration within another component

 

There are a number of reasons why this is bad. 

 

  1. Performance. In every render of a parent's component, a new declaration function is created for the inner component. During each render cycle, the inner component's lifecycle methods will be called. This will cause performance issues as well as losing the previous state.

 

  1. There is a lot of coupling in the code. A component's scope becomes dependent upon that of its parent.

 

  1. It is almost impossible to reuse inner components. The inner components cannot be exported, they can only be passed as props further down the scope, which is not optimal.

 

The components should be kept in their respective files to avoid this issue.

 

Props are used sometimes in Initial State

 

For generic components such as counter components, it is perfectly fine to use the initial state from the official React docs.

 

The goal of this process is to initialize the state of a component with a non-reactive prop by setting props to state. 

 

Outside of the example, an initial react state should not be set to a reactive property value.

 

Why?

 

 

Because that state cannot be changed until a setState function is called. 

 

Properties from the upper level will be received by the component, but the state will remain unchanged.

 

Components can no longer rely on the concept of a single source of truth.

 

Such behavior is risky and should not be encouraged.

 

Index as a Key

 

 

React allows you to render multiple items using the array.map method.

 

The element or component key must be unique so that React can properly track it. 

 

The index can sometimes be a duplicate key, so you should avoid using it as a key.

 

Let's say you have an array of items that will be rendered via .map and the index keys are going to be used.

 

Imagine the array being expanded or contracting in the middle.

 

Key will become the same, and React will be the same identical element/component as before.

 

This might result in undesirable effects and should be avoided.

 

Frequent use of the spread operator

 

When used correctly, spread operators are great for reducing code and managing it in a more clear manner.

 

In cases where reusable components or new data objects can be created that reuse data, spread operators are very useful.

 

They are even useful when passing arguments into functions. 

 

It is common for developers to make the mistake of using a spread operator on props, resulting in the wrong or undesired props being set on a component.

 

This can cause errors on the console. 

 

useEffect, useMemo & useCallback dependencies

 

Dependencies are included in the stated React hooks.

 

Dependencies are merely an array of items that trigger updates when they are changed. 

 

It can be difficult to manage dependencies if you haven't tried it before.

 

A dependency array should contain items relating to hooks and not be overcrowded with them.

 

The static analysis rule in ESLint can be used to help us rely on dependencies in hooks.

 

Use useEffect once when mounting the component, so it is only possible to leave the dependencies array empty.

 

Doing Premature Optimizations 

 

Optimizations are usually a good thing, but they should not be applied to every single piece of information. 

 

Use hooks such as useMemo, useCallback, and PureComponents to reap the benefits of memoization. 

 

If developers are not very focused, it can lead to the breakage of memos one by one.

 

A TypeScript Type is Declared Incorrectly

 

TypeScript has become a necessity for many developers in JS and most people know about its keywords such as any, never, and unknown. 

 

Unknown variables may have any value assigned to them since any possible value can be assigned to them.  

 

This is the type-safe counterpart of Ever, as it represents an empty set, meaning no value can be assigned to such a variable. 

 

These keywords should be avoided most of the time. This cannot be overstated.

 

Many developers are frustrated with TypeScript and then just add one of these keywords to get it off their backs.

 

This is bad practice.

 

Using these keywords has a place, but they must be used scarcely:

 

  • You can use unknown to indicate there will be a value of any type.

 

  • Any unsafe escape hatch will do if you really need it.

 

  • Place never in a position where a value won't or shouldn't exist.

 

 

Final Thought

 

We saw a number of bad patterns today and we also learned how to avoid them and use proper patterns.

 

It will make your life as a programmer much easier and prevent many bugs and potential refactorings if you learn how to avoid these bad patterns.

 

Work with world leading tech businesses

We connect high-performing software engineer talent in the Philippines with some of the world’s leading and most innovative Tech companies.

Submit CV
career3

Author

Jake_Hall_Feb2021-11
Jake Hall
Chief Technology Officer
Work with world leading tech companies from the Philippines

Be up to date!

Sign up for our newsletters and get our latest outsourcing and tech news, and exclusive promotions.

Cloud-employeeCover

If you’re interested to know more about our employee benefits and perks, you can download the booklet.

Download Now

Submit your CV today

One of our recruitment officers will get in touch with you!

    Our live jobs

    • Senior Front - End Developer - ANGULAR 6+

      Work with a leading UK company that works across multiple verticals within professional services globally, and has a skilled development team of 70 working remotely, operating across multiple continents. This is an outstanding opportunity for interested candidates to join a diverse team of experts, utilising some of the newest leading practises within frontend development.

    • Senior Full-Stack Ruby on Rails Developer

      A UK based award-winning Edutech platform business, working with Health & Social care organisations to ensure front line teams are fully trained and ready to help those in need. The company has seen an explosion of traction since Covid and their vision is to help save people’s lives.

    • Ruby on Rails Developer

      As the sole developer in the team, you'll lead on all aspects and have a leading hand in shaping the future of the platform, working from back to front and playing a crucial part in the design, development and production of quality code. We're a close knit, remote working team and as such, you'll need to be self motivated and goal driven to keep everything moving at pace.

    • Senior PHP / Laravel Developer

      A leading UK company and is rapidly growing and recognised for their innovative service capabilities. With a legacy of many years at the forefront of the technology industry, they operate both nationally and internationally and place a premium on honesty, commitment and teamwork. With a solution strategically designed to support the ever-changing needs of service providers.

    • Senior Fullstack.Net Developer

      The company offers product and service stack presents end-to-end solutions for travel agents, tour operators, loyalty brands, hotels, conference destinations, OTAs and tourism organisations.

    • React JS Developer

      UK Company specialises in CRM memberships and subscription end clients.

    • Senior C++ Developer 14/17

      A UK leading institutional-grade exchange for trading asset-backed tokens (digital securities, security tokens, etc.).

    • React JS Developer

      A leading UK company well established in creating content apps and websites for their clients.

    • Dynamics 365 Expert

      IT and Microsoft Gold Partner specialising in Azure, Microsoft 365 and Dynamics 365.

    • Full Stack Developer - React & .Net

      IT and Microsoft Gold Partner specialising in Azure, Microsoft 365 and Dynamics 365.

    How many hours do you want the developer to dedicate to working with you?

    What skillsets are you looking to hire?

    When do you need your developer to start ?