DEV Community

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

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

Nicolas B. on November 27, 2023

1 - Optimizing Parameter Checks ❌ Stop this: if (userRole !== 'admin' && userRole !== 'moderator' && userR...
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 !!

Collapse
 
duongductrong profile image
Trong Duong

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

const objectCopy = structuredClone(originalObject) <---

I think that's maybe the old browser cannot work with structuredClone