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 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.
Different text cases
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 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.
Defining highly reusable components using stateless functions is a brilliant idea. There is no state in them; they are only functions.
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.
JSX spread attributes
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.
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.
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.
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.
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.
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:
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 can render child components of many types. In most cases, it’s either an array or a string.
Array as children
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.
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.
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.
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.
Accessing a Child Component
DOM elements and React elements you create yourself can be accessed by React references.
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.
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.
So far, so good, but spreading props into an HTML DOM element is a bad practice.
The above code will give an error, just like the one given below, because the div element has no property called foo:
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.