Skip to content
loading...

What are Your Best Practices for Writing React Code

github logo ・1 min read  

React JS has lot of complexity in terms of concept for beginners. And there multiple ways of doing things. I am sure all of us have different approach to writing code, testing it and deploying it.

So my question is for those who have set some flow or process for react projects.

What are some of the practices that you follow while working on react project?

twitter logo DISCUSS (3)
markdown guide
 

Use Stateless Functional Components wherever possible. This helps to reduce code bloat and just makes things easier to read. Also try to avoid hard coding data into the components. Hard coding data makes it less reusable because it can only be used in very specific cases.

I'm not sure if it's best practice or just personal preference, but I know some people also like to create an object containing the items they're passing into a component as props for instance ({this, is, a, prop}) => {}. I'm lazy and just do (props) => {}. I'd be curious to find out what other's preferences are about this.

 

When working with a component's state, clone the state while assigning it to a new variable.

ex.

let item = this.state.item; // (No)
let item = {...this.state.item}; // (Do this instead)
let item = [...this.state.items] // (Or do this if it's an array)

Ran into issues, especially in multi-person teams, where we'd forget that item references the component's state. item would later get reassigned, or properties get changed, and then component's state is mutated!

 

Making sure my containers are lean with less rendering. Most of the DOM rendering is handled by the functional components.

Classic DEV Post from Jun 22 '19

Do you have your own Gatsby site? Let's brainstorm a dev.to cross-poster

I'd love it if my blog posts were automatically sent to dev.to - wouldn't you?

Mahesh K profile image
I write (about) code and keep interest in Data science, Venture Funding and startups.