DEV Community šŸ‘©ā€šŸ’»šŸ‘Øā€šŸ’»

Mahesh K
Mahesh K

Posted on

What are Your Best Practices for Writing React Code

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?

Top comments (3)

Collapse
 
iam_timsmith profile image
Tim Smith

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.

Collapse
 
ganderzz profile image
Dylan Paulus • Edited on

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!

Collapse
 
olivermensahdev profile image
Oliver Mensah

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

šŸ‘€ Just want to lurk?

That's fine, you can still create an account and turn on features like šŸŒš dark mode.