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

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

???? French version : https://brdnicolas.com/fr/articles/stop-this-use-instead-js

1 - Optimizing Parameter Checks

? Stop this:

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

? Use instead:

const allowedRoles = ['admin', 'moderator', 'user'];

if (!allowedRoles.includes(userRole)) {
        console.error('Invalid user role');
}
        

2 - useReducer for toggle states

? Stop this:

const [isModalVisible, setIsModalVisible] = useState(false)

setIsModalVisible((prevState) => !prevState)
        

? Use instead:

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

toggleModalVisibility()
        

3 - Destructured Objects as Parameters

? Stop this:

const processUserData = (firstName, lastName, age, email) => {
    ....
}

processUserData("Toto", "Tata", 35, "tototata@gmail.com");
        

? Use instead:

const processUserData = ({ firstName, lastName, age, email }) => {
    ....
}

processUserData({
    firstName: "Toto",
    lastName: "Tata",
    age: 35,
    email: "tototata@gmail.com"
});
        

4 - Efficient Object Cloning

? Stop this:

const originalObject = {
    key1: 'value1',
    key2: {
        key2a: () => console.log('value2a')
    }
}

const objectCopy = originalObject
        

? Use instead:

const originalObject = {
    key1: 'value1',
    key2: {
        key2a: () => console.log('value2a')
    }
}

const objectCopy = structuredClone(originalObject)
// or
const objectCopy = {...originalObject}
        

5 - Use Set to efficiently manage unique values

? Stop this:

const uniqueItemsArray = ['Apple', 'Banana', 'Orange', 'Banana', 'Apple'];

// Adding new items to the Array
uniqueItemsArray.push('Grapes');
uniqueItemsArray.push('Orange'); // Already exists but added again

// Checking if a value exists in the Array
const hasGrapes = uniqueItemsArray.includes('Grapes');

// Deleting an item from the Array
uniqueItemsArray = uniqueItemsArray.filter(item => item !== 'Banana');

uniqueItemsArray.forEach(item => {
  console.log(item);
});
        

? Use instead:

const uniqueItemsSet = new Set(['Apple', 'Banana', 'Orange', 'Banana', 'Apple']);
// will show ['Apple', 'Banana', 'Orange']

// Adding new unique items to the Set
uniqueItemsSet.add('Grapes');
uniqueItemsSet.add('Orange');

// Checking if a value exists in the Set
const hasGrapes = uniqueItemsSet.has('Grapes');

// Deleting an item from the Set
uniqueItemsSet.delete('Banana');

// Iterating through the Set
for (let item of uniqueItemsSet) {
  console.log(item);
}
        

My Linkedin

My X

My portfolio


要查看或添加评论,请登录

Nicolas B.的更多文章

社区洞察

其他会员也浏览了