The Talent500 Blog
React best practices and design patterns 1

React best practices and design patterns

Nearly 50 million projects use React every month as a frontend UI library. With more than nine years of dominance in the web development space, React is backed by Facebook and has several notable customers (including startups and Fortune 500 companies).

In recent times, React has received a lot of attention due to its relatively shallow learning curve. But following the best practices and industry standards is what most developers lack. Most likely, you will work with a  team of React developers. In order to work as a team, you need to follow some semantics and patterns that everyone can understand. Your code should be maintainable and reusable. If you have hundreds of components, managing your application will be difficult if you don’t follow some patterns.

In this detailed blog, we will cover various best practices while coding in React as well as some design patterns that you should know as a React developer. So let’s get started!

File organization in React

When working with React, you will have many files and folders in your project directory, it is recommended to have distinct folders so that your application can be maintained.

React best practices and design patterns 2

React folder structure

There is no one best file structure, but it is important to keep your files organized. Every component in React has at least one file associated with it, so your file structure will grow rapidly. Organize CSS, images, and fonts in a folder called assets. 

Naming convention in React

The naming of files and folders is one of the simplest tasks a developer can perform. Nevertheless, it is a very important one. Having a well-named file or folder can make it easier for you and other developers to find and understand your code.

When naming files and components, we often use Pascal Case or Camelcase. There are still a variety of cases developers use, such as the kebab case, the snake case, etc.

React best practices and design patterns 3

Different text cases

Reusable components

React is known for its ability to handle large components. However, if we break them into smaller pieces, we can reuse them. Reading, testing, maintaining, and reusing small components is easier. 

You can create a component, such as a widget, and import it on all the other components you require, eliminating the need for duplicate code. You can increase a component’s ability to be reused by designing it with a single function. 

Maintain a structured import

Since React is not an all-encompassing library, if you are a React developer, you are already aware that we import a lot of community libraries. We also import various style files, utils files, component files, and other files as necessary. The import section needs to maintain a sensible organizational structure or group in order to keep the code readable and maintainable.

React best practices and design patterns 4


React import structure

Remove unnecessary comments from the Code

It is important that the code we write is self-explanatory and not limited only to React.Make sure you only add comments where they are needed in order to avoid confusion when changing the code in the future. While going through the production, remove any unnecessary code such as console.logs(), alerts(), and other unused codes.

Stateless function

Defining highly reusable components using stateless functions is a brilliant idea. There is no state in them; they are only functions.

React best practices and design patterns 5

Stateful component

Components that store state are referred to as stateful components. Class components or functional components with hooks are both examples of stateful components. It is also called a container component, i.e, a container does data fetching and then renders its corresponding sub-component.

React best practices and design patterns 6
JSX spread attributes

Spread attributes are a JSX feature. It is syntactic sugar for passing every property of an object as JSX attributes. We can quickly copy all or a portion of an existing array or object into another array or object using the JavaScript spread operator (…).

React best practices and design patterns 7

Do not define a function inside render.

The tendency of React developers to define or create functions inside the render frequently leads to unexpected errors. It’s best to avoid defining a function inside the render. Try to keep the logic inside the render to an absolute minimum.

React best practices and design patterns 8

Destructuring

The destruction shown assigns properties of an object to variables of the same name. The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

React best practices and design patterns 9

Index as keys

React requires you to add a key prop to your element when creating an array of JSX elements. This is commonly done via a map function which in turn results in people using the index which is returned and set to the key property. This is an anti-pattern!
Arrays are collapsible, so React uses the key property to track each element. This can easily result in incorrect information being displayed.
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

React best practices and design patterns 10

Unnecessary divs should be avoided.

React developers tend to use divs to wrap the entire component, and sometimes it is not a good idea to follow this approach.

React best practices and design patterns 11

An alternate way of doing this is using a fragment, <React.Fragment> was introduced in React v16.2, we can use them instead of the several <div> tag.

React best practices and design patterns 12

Always name the components

It is recommended to have names for the components. Some new React developers have a bad habit of creating components without giving them names. You should always give names to the components. Utilizing React Dev Tools will enable you to track the error.

React best practices and design patterns 13

Conditional rendering

In React, you can create distinct components that encapsulate the behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript.
You can’t use regular if/else conditions inside a component definition. You can use the ternary operator to achieve the same.

Here are some examples of condition rendering in action:

If

React best practices and design patterns 14Unless

React best practices and design patterns 15

If else

React best practices and design patterns 16
Avoid nested Ternary Operators

Ternary operators are useful when we want to render something based on certain conditions. It is ideal for small cases, but when we nest ternary operators for checking more than one condition, it makes the code complex and hard to maintain.

React best practices and design patterns 17

Children types

React can render child components of many types. In most cases, it’s either an array or a string.

String

React best practices and design patterns 18

Array

React best practices and design patterns 19

Function

React best practices and design patterns 20

Array as children

We can iterate over an array, and we can provide an array as children. This is one of the common patterns in React. We can use the JavaScript map method to iterate through the elements for every value!

React best practices and design patterns 21

 

Function as children

Functions as child components let you pass a render function as the children prop to a component, allowing you to change what can be passed as children.

React best practices and design patterns 22
Unidirectional data flow

One-way direction data flow eliminates multiple states and deals with only one which is usually inside the store. To achieve that, our Store object needs logic that allows us to subscribe for changes.

React best practices and design patterns 23

Controlled and uncontrolled input

An input form element whose value is controlled by React is called a controlled component. A controlled input accepts its current value as a prop, as well as a callback to update that value, that’s the point of React.

React best practices and design patterns 24

 

Uncontrolled input is like traditional HTML form input:

A form element becomes “controlled” if you set its value via a prop. Controlled states are preferred over uncontrolled ones as they are easier to manage.
React best practices and design patterns 25
Accessing a Child Component

DOM elements and React elements you create yourself can be accessed by React references.

React best practices and design patterns 26

Mutating State without setState()

When we try to change the state of our component without using setState() it causes state changes without making the component re-render. Whenever setState gets called in the future, the mutated state gets applied.

React best practices and design patterns 27

Spreading props on DOM elements

When we spread props, we run into the risk of adding unknown HTML attributes, which is a bad practice. We usually spread the properties to the elements to avoid writing every single one manually.

React best practices and design patterns 28

So far, so good, but spreading props into an HTML DOM element is a bad practice.

React best practices and design patterns 29

The above code will give an error, just like the one given below, because the div element has no property called foo:

React best practices and design patterns 30

There are many more React patterns and antipatterns that you will find if you dig a little deeper. One thing to note is that we should also follow the semantic structure, for example, using semantic HTML tags like “section, “article,” etc. 


Wrapping It Up!

Congratulations on reaching this far! You’re a fantastic reader! In this detailed blog, we looked at various patterns that we should follow while using React. Not only did we experiment with React, but we also discussed various best practices and how to implement them with simple snippets.

Now you know how to build your React application in the most effective and efficient way.

Happy Reacting!

0
Afreen Khalfe

Afreen Khalfe

A professional writer and graphic design expert. She loves writing about technology trends, web development, coding, and much more. A strong lady who loves to sit around nature and hear nature’s sound.

Add comment