DEV Community

5 tips to improve your React and JS code

Adán Carrasco on March 15, 2020

Two weeks ago I started to work in a new project where some code was already written. However, there wasn't any best practices to follow. Something...
Collapse
 
marklai1998 profile image
Mark Lai •

For the first Tip
manually order the imports is tedious
I'm using import-sort with husky pre-commit hook
That makes my life much easier, I never need to care about the ordering of it
Just use auto import and commit + push my code, really simple
github.com/renke/import-sort

Collapse
 
s0xzwasd profile image
John Doe •

Thanks for sharing!

Collapse
 
adancarrasco profile image
Adán Carrasco •

This is so cool Mark. What a nice way to do it; automating it!
Thanks for sharing!

Collapse
 
jkhaui profile image
Jordy Lee •

These are great. Another simple tip is to always format your code (and ideally, to one of the widely accept standards, e.g. 2 spaces for indents). Nothing annoys me more than seeing unformatted code - it only takes 2-3 keypresses to fix!

Collapse
 
adancarrasco profile image
Adán Carrasco •

This is a really good tip! Totally agree with you.

Collapse
 
seanmclem profile image
Seanmclem •

In #5, you're manually setting user.flag before passing it to setUser. Does that cause any issues with immutablity? Normally I would do something like setUser({...user, flag}), but if I could save myself that step I would like to.

Collapse
 
mjnlonzame profile image
mjnlonzame •

Hello, user.flag is not a state

Collapse
 
seanmclem profile image
Seanmclem •

User is. So isn't user.flag? It's on the user object created with usestate

Collapse
 
sunnie profile image
sunnie •

Hello,In #5 API.js
export const fetchUser = async (errorHandler) => {
try {
const user = await axios.get('/user/25')
} catch(error) {
errorHandler(error)
}
}

Is there need to return ‘user ’?

Collapse
 
iammgk profile image
Mateen Kadwaikar •

Thaks a ton

Collapse
 
s0xzwasd profile image
John Doe •

Thanks for the 4 point, very valuable!

Collapse
 
idanen profile image
Idan Entin •

A better refactor of #5 would be to extract the logic to a custom hook.
That way it won't be coupled to the UserProfile component

Collapse
 
adancarrasco profile image
Adán Carrasco •

Hi Idan, in this case the UserProfilePage component has the logic decoupled from the User component. The User component is a presentational component while your UserProfilePage holds the Business Logic, this follows Atomic Design. bradfrost.com/blog/post/atomic-web...
Please let me know if you think otherwise. :)

Collapse
 
idanen profile image
Idan Entin •

The logic is decoupled, however not reusable.
So if you need the same logic in, say, Comments component, you'd need to write a CommentsPage.
You can avoid that by changing UserProfilePage to useUserProfile and have it return the user instead of JSX.
Small change, with large benefits