Stop this, use this instead : Top 5 best practices JS / React

Stop this, use this instead : Top 5 best practices JS / React

Nov 27 2023

1 - Optimizing Parameter Checks

❌ Stop this:

1if (userRole !== 'admin' && userRole !== 'moderator' && userRole !== 'user') {
2   console.error("Invalid user role")
3}

✅ Use instead:

1const allowedRoles = ['admin', 'moderator', 'user'];
2
3if (!allowedRoles.includes(userRole)) {
4        console.error('Invalid user role');
5}

2 - useReducer for toggle states

❌ Stop this:

1const [isModalVisible, setIsModalVisible] = useState(false)
2
3setIsModalVisible((prevState) => !prevState)

✅ Use instead:

1const [isModalVisible, toggleModalVisibility] = useReducer((currentValue) => !currentValue, false)
2
3toggleModalVisibility()

3 - Destructured Objects as Parameters

❌ Stop this:

1const processUserData = (firstName, lastName, age, email) => {
2    ....
3}
4
5processUserData("Toto", "Tata", 35, "tototata@gmail.com");

✅ Use instead:

1const processUserData = ({ firstName, lastName, age, email }) => {
2    ....
3}
4
5processUserData({
6    firstName: "Toto",
7    lastName: "Tata",
8    age: 35,
9    email: "tototata@gmail.com"
10});

4 - Efficient Object Cloning

❌ Stop this:

1const originalObject = {
2    key1: 'value1',
3    key2: {
4        key2a: () => console.log('value2a')
5    }
6}
7
8const objectCopy = originalObject

✅ Use instead:

1const originalObject = {
2    key1: 'value1',
3    key2: {
4        key2a: () => console.log('value2a')
5    }
6}
7
8const objectCopy = structuredClone(originalObject)
9// or
10const objectCopy = {...originalObject}

5 - Use Set to efficiently manage unique values

❌ Stop this:

1const uniqueItemsArray = ['Apple', 'Banana', 'Orange', 'Banana', 'Apple'];
2
3// Adding new items to the Array
4uniqueItemsArray.push('Grapes');
5uniqueItemsArray.push('Orange'); // Already exists but added again
6
7// Checking if a value exists in the Array
8const hasGrapes = uniqueItemsArray.includes('Grapes');
9
10// Deleting an item from the Array
11uniqueItemsArray = uniqueItemsArray.filter(item => item !== 'Banana');
12
13uniqueItemsArray.forEach(item => {
14  console.log(item);
15});

✅ Use instead:

1const uniqueItemsSet = new Set(['Apple', 'Banana', 'Orange', 'Banana', 'Apple']);
2// will show ['Apple', 'Banana', 'Orange']
3
4// Adding new unique items to the Set
5uniqueItemsSet.add('Grapes');
6uniqueItemsSet.add('Orange');
7
8// Checking if a value exists in the Set
9const hasGrapes = uniqueItemsSet.has('Grapes');
10
11// Deleting an item from the Set
12uniqueItemsSet.delete('Banana');
13
14// Iterating through the Set
15for (let item of uniqueItemsSet) {
16  console.log(item);
17}

My Linkedin

My X

My portfolio

See more articles