DEV Community

Cover image for Stop this, use this instead : Top 5 best practices JS / React
Nicolas B.
Nicolas B.

Posted on • Edited on

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

1 - Optimizing Parameter Checks

❌ Stop this:

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

✅ Use instead:

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

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

2 - useReducer for toggle states

❌ Stop this:

const [isModalVisible, setIsModalVisible] = useState(false)

setIsModalVisible((prevState) => !prevState)
Enter fullscreen mode Exit fullscreen mode

✅ Use instead:

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

toggleModalVisibility()
Enter fullscreen mode Exit fullscreen mode

3 - Destructured Objects as Parameters

❌ Stop this:

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

processUserData("Toto", "Tata", 35, "tototata@gmail.com");
Enter fullscreen mode Exit fullscreen mode

✅ Use instead:

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

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

4 - Efficient Object Cloning

❌ Stop this:

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

const objectCopy = originalObject
Enter fullscreen mode Exit fullscreen mode

✅ Use instead:

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

const objectCopy = structuredClone(originalObject)
// or
const objectCopy = {...originalObject}
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

✅ 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);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (16)

Collapse
 
oculus42 profile image
Samuel Rouse

This is a great list of suggestions! I definitely push for #1 in code reviews all the time.

I am on the fence about #2, though. There are times it's useful to pass a specific state rather than having to check to see if we need to toggle. It could be written to support an optional forced value, which would cover both possibilities.

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

// Regular toggle
toggleModalVisibility();

// Force a state
toggleModalVisibility(false);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
seandinan profile image
Sean Dinan

Woah -- how had I not learned about the nullish coalescing operator ?? until today 😯

I think I could sub it in for most of my ||s and it would be more syntactically accurate.

Collapse
 
brdnicolas profile image
Nicolas B.

Yeah! Pretty good suggestion thank's! :)

Collapse
 
oliie profile image
Oliver Praesto

Regarding #4 - Efficient Object Cloning
It's good to know that the spread variant won't work as expected:

const objectCopy = {...originalObject}
Enter fullscreen mode Exit fullscreen mode

That is because spreading will only do a shallow copy, but keep it's references to deep objects.

Example:

objectCopy.key2.key2a = "hello"
console.log(originalObject.key2.key2a) // "hello"
Enter fullscreen mode Exit fullscreen mode

So in that case, the structuredClone is better to use.

Collapse
 
manchicken profile image
Mike Stemle • Edited

I wish you had explained the “why” here. As-is, this reads doctrinaire, especially since constructs like Set are only more efficient once you achieve a greater n size.

Collapse
 
seandinan profile image
Sean Dinan • Edited

Strongly agree on #1 and #3!

Out of curiosity, what's the benefit of going with useReducer over useState in #2?

Since we use lots of toggles, I've got it abstracted out to a custom hook that lets you either just toggle it (99% of the time) or force-set a value (a few rare instances):

// useToggle.js

import { useState } from 'react';

export function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);

  const toggle = (bool) => {
    if (bool !== undefined) setValue(bool);
    else setValue((val) => !val);
  };

  return [value, toggle];
}

Enter fullscreen mode Exit fullscreen mode
// DemoComponent.jsx

import { useToggle } from '../useToggle';

export default function DemoComponent(){
  const [isLoading, toggleLoading] = useToggle(true);

  /* ... */

}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
brdnicolas profile image
Nicolas B.

You can make a custom hook too, I like the useReducer way because it's simple and easily readble. As @oculus42 said, you can give a custom value if you want

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

// Regular toggle
toggleModalVisibility();

// Force a state
toggleModalVisibility(false);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bop profile image
bop

The second option: why is that better?

Collapse
 
brdnicolas profile image
Nicolas B.

Hi @bop! It more simple and readable :)

Collapse
 
chkim116 profile image
changhoe_kim

Good very nice

Collapse
 
zakariathr22 profile image
Zakaria Tahri

Very nice 👍

Collapse
 
raulferreirasilva profile image
Raul Ferreira

Valuable tips, the first time I saw it I identified myself lol, I'm going to apply it to reduce my gigantic ifs. Thank you very much for sharing your knowledge 🦤.

Collapse
 
brdnicolas profile image
Nicolas B.

<3

Collapse
 
christianpaez profile image
Christian Paez

Very cool

Collapse
 
yogini16 profile image
yogini16

Nice article.
Thank you !!