d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

React Clean Code – DZone Web Dev

Clean code is more than just working code. Clean code is easy to read, simple to understand, and neatly organized. In this article, we’ll look at eight ways we can write cleaner React code.

When going through these suggestions, it’s important to remember that’s exactly what they are: suggestions. If you disagree with any of them, that’s completely fine. However, these are practices that I’ve found helpful in writing my own React code.

Let’s dive in!

1. Conditional Rendering Only for One Condition

If you need to conditionally render something when a condition is true and not render anything when a condition is false, don’t use a ternary operator. Use the && operator instead.

Bad example:

Good example:

2. Conditional Rendering on Either Condition

If you need to conditionally render one thing when a condition is true and render a different thing when the condition is false, use a ternary operator.

Bad example:

Good example:

3. Boolean Props

A truthy prop can be provided to a component with just the prop name without a value like this: myTruthyProp. Writing it like myTruthyProp={true} is unnecessary.

Bad example:

Good example:

4. String Props

A string prop value can be provided in double-quotes without the use of curly braces or backticks.

Bad example:

Good example:

5. Event Handler Functions

If an event handler only takes a single argument for the Event object, you can just provide the function as the event handler like this: onChange={handleChange}. You don’t need to wrap the function in an anonymous function like this: onChange={e => handleChange(e)}.

Bad example:

Good example:

6. Passing Components As Props

When passing a component as a prop to another component, you don’t need to wrap this passed component in a function if the component does not accept any props.

Bad example:

Good example:

7. Undefined Props

Undefined props are excluded, so don’t worry about providing an undefined fallback if it’s ok for the prop to be undefined.

Bad example:

Good example:

8. Setting State That Relies on the Previous State

Always set state as a function of the previous state if the new state relies on the previous state. React state updates can be batched, and not writing your updates this way can lead to unexpected results.

Bad example:

Good example:

Honorable Mentions

The following practices are not React-specific but rather good practices for writing clean code in JavaScript (or any programming language, for that matter).

  • Extract complex logic into clearly named functions.
  • Extract magic numbers into constants.
  • Use clearly named variables.

Happy coding!

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this