React Clean Code - Simple ways to write better and cleaner code

Tyler Hawkins - Feb 22 '21 - - Dev Community

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.

In going through these suggestions, it’s important to remember that that’s exactly what these 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 Mention

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

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

Happy coding!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .