3

Best coding practices in React.js

 2 years ago
source link: https://dev.to/hitanshimehta/best-coding-practices-in-reactjs-4gmp
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Best coding practices in React.js

Introduction:

In this article, we will discuss best coding practices that you can follow in your next project. These practices will make your code,

1) reusable
2) cleaner
3) efficient and
4) easily adaptable by another developer.

List of coding practices that you should follow.

1) Remove unnecessary props
2) Combine state
3) Separate UI and logic
4) In long component hierarchy use useContext
5) Write a function for a repetitive task
6) Avoid named import/member import
7) Use forEach instead of map

1) Combine state

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 help of an example.

Let's say you are working on a chocolate website.
You have two types of sizes.

1) Default size ---> You will receive sizes from API
2) Custom size ---> User can add custom sizes.

Once user has added custom sizes, user can proceed for checkout by selecting desired sizes.
In the wrong coding practice, you can have three different states.

1) state for default sizes (received from backend)
2) state for custom sizes
3) state for selected sizes

So you will define three different states.

const [APISizes, setAPISizes] = useState([{
id:''
height:'',
width:''
}]);

const [customSizes, setCustomSizes] = useState([{
id:''
height:'',
width:''
}]);

const [selectedSizes, setSelectedSizes] = useState([1,2]);

Now you have to keep an eye on three different state and you'll need to keep them in sync. Let's look at scenarios where it will create a problem.

1) While displaying all sizes you have to loop through two states. (on APISizes and customSizes)
2) In selectedSizes we are storing only ids. For size information we have to iterate over APISize and CustomSize.

In good coding practice, you can define a single state as follow.

const [userSuggestions, setUserSuggestion] = useState([{
id:1,
height:100,
width:100,
isCustom:false,
isSelected:false
}]);

In this case, you have to think about only one state. If another developer works on your code it's easy for her/him too.

In this coding practice, If you want to introduce a new key, you have to update only one state instead of 2-3 states.

const [userSuggestions, setUserSuggestion] = useState([{
id:1,
height:100,
width:100,
isCustom:false,
isSelected:false,
isByDefaultSelected:true,
}]);


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK