• How To Write Better Code In React
  • Author: Rajat S
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: jonjia
  • Proofread by jasonxia23, senior professor

9 practical tips for writing better React code: Understand code checking, propTypes, PureComponent, and more.

React makes it easy to create interactive interfaces. Design a simple view for each state in your application, and React efficiently updates and renders the correct components as the data changes.

In this article, I’ll show you some ways to become a better React developer. Everything from tools to code styles will help you improve your React skills. 💪


Code review

One of the most important things you can do to write better code is to use a good code review tool. If we have a set of code inspection rules configured, the code editor can help us catch any code problems that might occur.

But in addition to catching problems, ES Lint also keeps you learning best practices for React code.

import react from 'react'; /* Other imports */ /* Code */export default class App extends React.Component {
  render() {
    const { userIsLoaded, user } = this.props;
    if(! userIsLoaded)return <Loader />;
    
    return (
      /* Code */
    )
  }
}
Copy the code

Take a look at the code above. Suppose you want to reference a new property called this.props. Hello in the Render () method. The code review tool immediately turns the code red and says:

Props validation did not exist'hello' (react/prop-types)
Copy the code

The code review tool will introduce you to React best practices and shape your understanding of the code. Pretty soon, when you’re writing code later, you’ll start avoiding mistakes.

You can configure code checking tools for JavaScript by going to the ESLint website, or using Airbnb’s JavaScript Style Guide. You can also install the React ESLint Package.


propTypesAnd defaultProps

In the last section, I talked about how my code inspection tool works when using a prop that doesn’t exist.

static propTypes = {
  userIsLoaded: PropTypes.boolean.isRequired,
  user: PropTypes.shape({
    _id: PropTypes.string,
  )}.isRequired,
}
Copy the code

In this case, if userIsLoaded is not required, add a note to the code:

static defaultProps = {
 userIsLoaded: false,}Copy the code

So whenever we use parameter type checking in a component, we set a propType for it. As above, we told React: the userIsLoaded type is always a Boolean.

If we declare that userIsLoaded is not a required value, then we define a default value for it. There is no need to define a default value if it is required. However, the rule also states that you should not use ambiguous propTypes like objects or arrays.

The reason for using shape to validate user is that it requires an ID attribute of type string inside, and the entire User object is required.

Make sure that propTypes and defaultProps are declared for every component that uses props. This helps to write better React code.

The error log lets you know that either you are passing the wrong data or you are not getting the expected value, especially when writing reusable components, which makes it easier to find the error. This also makes these reusable components more readable.

Note:

React as of v15.5 no longer has propTypes built in and needs to be added to your projects as a separate dependency package.

Click on the link below to learn more:

  • prop-typesA tool for checking React props and similar object types at runtime

Know when to create a new component

export default class Profile extends PureComponent {
  static propTypes = {
    userIsLoaded: PropTypes.bool,
    user: PropTypes.shape({
      _id: PropTypes.string,
    }).isRequired,
  }
  
  static defaultProps = {
    userIsLoaded: false,}render() {
    const { userIsLoaded, user } = this.props;
    if(! userIsLoaded)return <Loaded />;
    return (
      <div>
        <div className="two-col">
          <section>
            <MyOrders userId={user._id} />
            <MyDownloads userId={user._id} />
          </section>
          <aside>
            <MySubscriptions user={user} />
            <MyVotes user={user} />
          </aside>
        </div>
        <div className="one-col">
          {isRole('affiliate', user={user._id) &&
            <MyAffiliateInfo userId={user._id} />
          }
        </div>
      </div>
    )
  }
}
Copy the code

There is a component called Profile. There are other components inside this component like MyOrder and MyDownloads. Because they get data from the same data source (User), you can write all of these components together. Turn these small pieces into one giant component.

While there are no hard and fast rules for when to create a new component, ask yourself:

  • Is the functionality of the code becoming cumbersome?
  • Does it only represent its own thing?
  • Do you want to reuse this code?

If the answer to any of the above questions is yes, then you need to create a new component.

Remember, anyone looking at your widget with 200-300 lines will freak out, and no one will ever want to look at your code again.


Component vs PureComponent vs Stateless Functional Component

For a React developer, it is important to know when to use Component, PureComponent, and Stateless Functional Component in your code.

You may have noticed in the code above that I didn’t inherit a Profile from Component, but PureComponent.

First, let’s look at stateless functional components.

Stateless Functional Component (Stateless Functional Component)

const Billboard = () => (
  <ZoneBlack>
    <Heading>React</Heading>
    <div className="billboard_product">
      <Link className="billboard_product-image" to="/">
        <img alt="#" src="#">
      </Link>
      <div className="billboard_product-details">
        <h3 className="sub">React</h3>
        <p>Lorem Ipsum</p>
      </div>
    </div>
  </ZoneBlack>
);
Copy the code

Stateless functional components are a very common component type. It gives us a very concise way to create components that don’t use any state, refs, or lifecycle methods.

Stateless functional components are characterized by having no state and only one function. So you can define a component as a constant function that returns some data.

Simply put, stateless functional components are functions that return JSX.

PureComponents

Normally, a component gets a new prop and React rerenders the component. Sometimes, though, a newly passed prop doesn’t really change, and React still triggers a re-render.

Using PureComponent can help you avoid this wasteful re-rendering. For example, if a prop is a string or a Boolean and it changes, PureComponent will recognize the change, but if prop is an object and its properties change, PureComponent will not trigger rerendering.

So how do you know when React triggers an unnecessary re-render? Check out the React package called Why Did You Update. This package notifies you in the console when unnecessary re-rendering occurs.

Once you have identified an unnecessary re-rendering, you can avoid it by replacing Component with PureComponent.


Use the React developer tool

If you really want to be a professional React developer, you should always use the React developer tool during development.

If you use React, your console probably advised you to use the React developer tool.

The React developer tool works with all major browsers, such as Chrome and Firefox.

With the React developer tool, you can see the entire application structure and the props and states being used in the application.

The React developer tool is a great way to explore the React component and diagnose problems in your application.


Use inline conditional statements

This point may be controversial, but I’ve found that using inline conditional statements significantly simplifies my React code.

As follows:

<div className="one-col">
  {isRole('affiliate', user._id) &&
    <MyAffiliateInfo userId={user._id} />
  }
</div>
Copy the code

In the code above, there is a method to check if the person is “affiliate” followed by a component called
.

The benefits of this are:

  • You don’t have to write a separate function
  • You don’t have to use the “if” statement in the Render method
  • You don’t have to create “links” for other locations in the component

Using inline conditional statements is very compact. To start, you can set the condition to true, and the
component will be displayed no matter what.

Then we use && connection criteria and
. This will render the component when the condition is true.


Use snippet libraries whenever possible

Open a Code editor (I’m using VS Code) and create a new JS file.

Type rc in this file and you will see the following prompt:

Pressing enter immediately yields the following code snippet:

The advantage of these snippets is not only to help you reduce bugs, but also to help you get the latest and greatest writing.

You can install many different snippet libraries in the code editor. What I use for VS Code is ES7 React/Redux/ react-native /JS Snippets.


React Internals– Know how React works internally

React Internals is a series of five articles that help me understand the basics of React and ultimately help me become a better React developer!

React Internals can help you understand when and how to do the right thing in React if you don’t fully understand certain issues or if you know how React works.

This is especially useful for people who don’t know where to execute code.

Understanding the inner workings of React will help you become a better React developer.


Use it in your componentBit 和 StoryBook

Bit is a tool that turns your UI components into building blocks that can be shared, developed, and synchronized across different applications.

You can also manage team components with Bit, making them easy to access and use, as well as test individually, through the online component area.

  • Bit – Share co-create code componentsBit makes building software with widgets easier and more fun. Share and synchronize these components across your team

Storybook is a rapid development environment for UI components that helps you navigate through a library of components, see the different states of each component, and develop and test components interactively.

Storybook provides an environment for you to quickly develop React components. It allows you to see the components in real time as the Web page is updated hot when you manipulate their properties.


Quickly review

  1. Use the code checking tool, using the ESLint, Airbnb’s JavaScript Style Guide, and ESLint React plugins.
  2. Use propTypes and defaultProps.
  3. Know when to create a new component.
  4. Know when to use Component, PureComponent, and Stateless Functional Component.
  5. Use the React developer tool.
  6. Use inline conditional statements.
  7. Use snippet libraries to save time wasted on boilerplate code.
  8. Learn how React works with React Internals.
  9. Use tools like Bit and StoryBook to optimize the development process.

The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.