Домой United States USA — software Best Coding Practices in ReactJS

Best Coding Practices in ReactJS

180
0
ПОДЕЛИТЬСЯ

Let’s discuss the best coding practices that you can follow in your next project to make the code clean, efficient, and easily adaptable by another developer.
Join the DZone community and get the full member experience. In this article, we will discuss the best coding practices that you can follow in your next project. These practices will make your code reusable, cleaner, efficient, and easily adaptable by another developer. In most of the components, you’ll have a state. While defining a new state, take time and think if you can combine multiple states into a single state. Let’s understand this with the help of an example. Let’s say you are working on a chocolate website and you have two types of sizes: Default size: You will receive sizes from API. Custom size: Users can add custom sizes. Once the user has added custom sizes, he/she can proceed for checkout by selecting desired sizes. In the wrong coding practice, you can have three different states. Now you have to keep an eye on three different states and you’ll need to keep them in sync. Let’s look at scenarios where it will create a problem. While displaying all sizes you have to loop through two states including APISizes and customSizes. In selectedSizes we are storing only ids but for size information, we have to iterate over APISize and CustomSize. In good coding practice, you can define a single state as follow. In this case, you have to think about only one state and if another developer works on your code it’s easy for her/him too. Additionally, If you want to introduce a new key, you have to update only one state instead of 2 or 3 states. In a long component hierarchy, useContext will provide cleaner and reusable code. Look at the following example: In the application, you can select a project and folder. In the dashboard component, we want to show the total selected projects and folders and for that we need to define two states in the dashboard component: We will pass these states from: Selected project: Dashboard -> Projects -> Project Display -> Project Option. Selected folder: Dashboard -> Folders -> Folder display -> Folder Option.

Continue reading...