By Tyler Hawkins

Dev. To /thawkin3/re…

Clean code isn’t just code that works, it’s easy to read, easy to understand, and organized.

In this article, we’ll look at eight ways to clean code.

As you read these suggestions, remember that these are just suggestions! If you don’t agree with any of them, that’s totally fine.

Here are some of the practices I’ve found useful in writing my Own React code.

Let’s get started!

1. Render only one condition

If you need to render something when the condition is true and nothing when the condition is false, do not use ternary expressions and use && instead.

Not recommended example:

import React, { useState } from 'react'

export const ConditionalRenderingWhenTrueBad = () = > {
  const [showConditionalText, setShowConditionalText] = useState(false)

  const handleClick = () = >
    setShowConditionalText(showConditionalText= >! showConditionalText)return (
    <div>
      <button onClick={handleClick}>Toggle the text</button>{/* conditionaltext */} {showConditionalText?<p>Condition is True!</p> : null} 
    </div>)}Copy the code

Recommended examples:

import React, { useState } from 'react'

export const ConditionalRenderingWhenTrueGood = () = > {
  const [showConditionalText, setShowConditionalText] = useState(false)

  const handleClick = () = >
    setShowConditionalText(showConditionalText= >! showConditionalText)return (
    <div>
      <button onClick={handleClick}>Toggle the text</button>
      {showConditionalText && <p>Condition is True!</p>}
    </div>)}Copy the code

2. Render each condition

If you need to render something when the condition is true and something else when the condition is false. Use ternary expressions!

Examples not recommended:

import React, { useState } from 'react'

export const ConditionalRenderingBad = () = > {
  const [showConditionOneText, setShowConditionOneText] = useState(false)

  const handleClick = () = >
    setShowConditionOneText(showConditionOneText= >! showConditionOneText)return (
    <div>
      <button onClick={handleClick}>Toggle the text</button>{/* Both True and False render contents */} {showConditionOneText &&<p>Condition is True!</p>} {! showConditionOneText &&<p>Conditions for Flase!</p>}
    </div>)}Copy the code

Recommended examples:

import React, { useState } from 'react'

export const ConditionalRenderingGood = () = > {
  const [showConditionOneText, setShowConditionOneText] = useState(false)

  const handleClick = () = >
    setShowConditionOneText(showConditionOneText= >! showConditionOneText)return (
    <div>
      <button onClick={handleClick}>Toggle the text</button>
      {showConditionOneText ? (
        <p>The condition must be true!</p>
      ) : (
        <p>The condition must be false!</p>
      )}
    </div>)}Copy the code

3. Boolean props

It is recommended that this parameter be omitted if the Props value is true.

Not recommended example:

import React from 'react'

const HungryMessage = ({ isHungry }) = > (
  <span>{isHungry ? 'I am hungry' : 'I am full'}</span>
)

export const BooleanPropBad = () = > (
  <div>
    <span>
      <b>This person is hungry: </b>
    </span>
    <HungryMessage isHungry={true} />
    <br />
    <span>
      <b>This person is full: </b>
    </span>
    <HungryMessage isHungry={false} />
  </div>
)
Copy the code

Recommended examples:

import React from 'react'

const HungryMessage = ({ isHungry }) = > (
  <span>{isHungry ? 'I am hungry' : 'I am full'}</span>
)

export const BooleanPropGood = () = > (
  <div>
    <span>
      <b>This person is hungry: </b>
    </span>{/* do not assign true, omit */}<HungryMessage isHungry />
    <br />
    <span>
      <b>This person is full: </b>
    </span>
    <HungryMessage isHungry={false} />
  </div>
)
Copy the code

4. String props

The Props value is String, using double quotes, without curly braces or back quotes.

Not recommended example:

import React from 'react'

const Greeting = ({ personName }) = > <p>Hi, {personName}!</p>

export const StringPropValuesBad = () = > (
  <div>
    <Greeting personName={"John} "/ >
    <Greeting personName={'Matt'} / >
    <Greeting personName={`Paul`} / >
  </div>
)
Copy the code

Recommended examples:

import React from 'react'

const Greeting = ({ personName }) = > <p>Hi, {personName}!</p>

export const StringPropValuesGood = () = > (
  <div>
    <Greeting personName="John" />
    <Greeting personName="Matt" />
    <Greeting personName="Paul" />
  </div>
)
Copy the code

5. Event handler functions

If an event function accepts only one argument, there is no need to pass in an anonymous function: onChange={e=>handleChange (e)}. The recommended writing is onChange={handleChange}.

Not recommended example:

import React, { useState } from 'react'

export const UnnecessaryAnonymousFunctionsBad = () = > {
  const [inputValue, setInputValue] = useState(' ')

  const handleChange = e= > {
    setInputValue(e.target.value)
  }

  return (
    <>
      <label htmlFor="name">Name: </label>{/* The event takes only one argument and does not require an anonymous function */}<input id="name" value={inputValue} onChange={e= > handleChange(e)} />
    </>)}Copy the code

Recommended examples:

import React, { useState } from 'react'

export const UnnecessaryAnonymousFunctionsGood = () = > {
  const [inputValue, setInputValue] = useState(' ')

  const handleChange = e= > {
    setInputValue(e.target.value)
  }

  return (
    <>
      <label htmlFor="name">Name: </label>
      <input id="name" value={inputValue} onChange={handleChange} />
    </>)}Copy the code

6. components as props

When you pass a component as an argument to another component, you do not need to wrap the passed component in a function if the component does not accept any arguments.

Not recommended example:

import React from 'react'

const CircleIcon = () = > (
  <svg height="100" width="100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
  </svg>
)

const ComponentThatAcceptsAnIcon = ({ IconComponent }) = > (
  <div>
    <p>Below is the icon component prop I was given:</p>
    <IconComponent />
  </div>
)

export const UnnecessaryAnonymousFunctionComponentsBad = () = >({/* Components do not need to be wrapped in functions */}
  <ComponentThatAcceptsAnIcon IconComponent={() = > <CircleIcon />} />
)
Copy the code

Recommended examples:

import React from 'react'

const CircleIcon = () = > (
  <svg height="100" width="100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
  </svg>
)

const ComponentThatAcceptsAnIcon = ({ IconComponent }) = > (
  <div>
    <p>Below is the icon component prop I was given:</p>
    <IconComponent />
  </div>
)

export const UnnecessaryAnonymousFunctionComponentsGood = () = > (
  <ComponentThatAcceptsAnIcon IconComponent={CircleIcon} />
)
Copy the code

7. Undefined props

If undefined is allowed, do not supply undefined as a fallback value.

Not recommended example:

import React from 'react'

const ButtonOne = ({ handleClick }) = > (
  <button onClick={handleClick || undefined} >Click me</button>
)

const ButtonTwo = ({ handleClick }) = > {
  const noop = () = > {}

  return <button onClick={handleClick || noop} >Click me</button>
}

export const UndefinedPropsBad = () = > (
  <div>
    <ButtonOne />
    <ButtonOne handleClick={()= >alert('Clicked! ')} / ><ButtonTwo />
    <ButtonTwo handleClick={()= >alert('Clicked! ')} / ></div>
)
Copy the code

Recommended examples:

import React from 'react'

const ButtonOne = ({ handleClick }) = > (
  <button onClick={handleClick}>Click me</button>
)

export const UndefinedPropsGood = () = > (
  <div>
    <ButtonOne />
    <ButtonOne handleClick={()= >alert('Clicked! ')} / ></div>
)
Copy the code

8. Set state to depend on the previous state

If the new state depends on the previous state, state is always set as a function of the previous state. React status updates can be batch processed.

Not recommended example:

import React, { useState } from 'react'

export const PreviousStateBad = () = > {
  const [isDisabled, setIsDisabled] = useState(false)

  const toggleButton = () = >setIsDisabled(! isDisabled)const toggleButton2Times = () = > {
    for (let i = 0; i < 2; i++) {
      toggleButton()
    }
  }

  return (
    <div>
      <button disabled={isDisabled}>
        I'm {isDisabled ? 'disabled' : 'enabled'}
      </button>
      <button onClick={toggleButton}>Toggle button state</button>
      <button onClick={toggleButton2Times}>Toggle button state 2 times</button>
    </div>)}Copy the code

Recommended examples:

import React, { useState } from 'react'

export const PreviousStateGood = () = > {
  const [isDisabled, setIsDisabled] = useState(false)

  {/* The recommended setting is function */}
  const toggleButton = () = > setIsDisabled(isDisabled= >! isDisabled)const toggleButton2Times = () = > {
    for (let i = 0; i < 2; i++) {
      toggleButton()
    }
  }

  return (
    <div>
      <button disabled={isDisabled}>
        I'm {isDisabled ? 'disabled' : 'enabled'}
      </button>
      <button onClick={toggleButton}>Toggle button state</button>
      <button onClick={toggleButton2Times}>Toggle button state 2 times</button>
    </div>)}Copy the code

Those are my recommended practices for writing clean React code.

Finally, I wish you a happy development!

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign