DEV Community

Cover image for 14 Beneficial Tips to Write Cleaner Code in React Apps

14 Beneficial Tips to Write Cleaner Code in React Apps

jsmanifest on August 18, 2019

Find me on medium Writing clean code is something that becomes mandatory at some point in your career especially while you're trying to obtain you...
Collapse
 
dance2die profile image
Sung M. Kim

Thank you for the great post as usual.

I agree with 10. Use useReducer if useState becomes complex not just because you can co-locate concerns but also because you can extract that functionality out as you mentioned in 6. Put Independent Functions Outside of Your Custom Hooks.

I had to create a context (using tips on How to use React Context effectively) and had very easy time make it into a context value.

Collapse
 
chrisachard profile image
Chris Achard

Good tips, thanks. In regards to "folderizing your components" - do you ever run into issues with so many files called "index.js"? That's just a little thing - but it always kind of confuses/bugs me when I have a bunch of index.js functions open, and I have to figure out which is which... Any tips for that?

Collapse
 
jsmanifest profile image
jsmanifest

No problem! And what I do is to not write anything in the index.js but to export default the actual file in the same directory.

src/components/Tooltip/index.js:

export { default } from './Tooltip'
import Tooltip from '../components/Tooltip'

You can also put a package.json in place of index.js as below:

src/components/Tooltip/package.json

{
  "main": "./Tooltip.js"
}
import Tooltip from '../components/Tooltip'

Either way the end goal is to write code in the actual Tooltip.js file.

Collapse
 
chrisachard profile image
Chris Achard

Ahhhh - got it. Thanks! that's a good idea.

Thread Thread
 
jsmanifest profile image
jsmanifest

No problem :)

Collapse
 
zarabotaet profile image
Dima • Edited
const removeFalseyImages = (images = []) => images.reduce((acc, img) => (img ? [...acc, img] : acc), [])

const removeFalseyImages = (images = []) => images.filter(Boolean)

Sorry don't read the whole article after this🀒😱

Collapse
 
monfernape profile image
Usman Khalil

You just showed an amazing list of good practices. Thanks for sharing them here

Collapse
 
jsmanifest profile image
jsmanifest

Your very welcome. Glad to hear that, Usman Khalil!

Collapse
 
k_penguin_sato profile image
K-Sato

Great post! Thank u!

Collapse
 
bwca profile image
Volodymyr Yepishev

I think you might be interested in sort-imports plugin for eslint, it's configurable and could potentially do the import sorting for you.
Nice article πŸ™‚