IO /how-to writ… bitsrc. IO /how-to writ…

How to write better React code

9 useful tips for writing better code in React: Use Linting, propTypes, PureComponent, and more.

React makes creating interactive UIs a breeze. Design a simple view for each state in your application, and React will effectively update and render the correct components as the data changes.

In this article, I’ll show you some tips to help you become a better React Developer.

I’ll cover everything from tools to actual code styles that can help you improve your React skills.


Linting

One of the most important things for writing better code is good linting.

Because if we set up a good set of Linting rules, your code editor will be able to catch anything that might cause problems in your code.

And rather than just catching problems, your ES Lint Settings will keep you up to date on React best practices.

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

Taking the code snippet above as an example, suppose you want to reference a new property called this.props. Hello in the Render () function. Your linter will immediately turn red and say:

'hello' is missing in props validation (react/prop-types)
Copy the code

Linting will help you understand best practices in React and refine your understanding of the code. Pretty soon, you’ll be writing code without making mistakes.

You can use ESLint to set up a Linting tool for JavaScript, or you can use Airbnb’s JavaScript style guide. You can also install the React ESLint package.


PropTypes and defaultProps

In the previous section, I talked about how my linter worked when I tried to pass an unproven prop.

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

Here, if we don’t need userIsLoaded, then we need to add the following code to our code:

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

Therefore, whenever a PropType is used in a component, we need to set a PropType for it. As in the example above, we need to tell React that userIsLoaded is always a Boolean.

Again, if we don’t pass userIsLoaded, then we’ll need a default Prop. If we pass userIsLoaded, then we don’t have to define a default Prop for it. However, this rule also states that you should not have vague propTypes like Object or array.

That’s why we use Shape to validate user, which contains another ID whose propType is string, and the entire User object is a mandatory argument.

Ensuring that propTypes and defaultProps are set on every component that uses prop will go a long way.

The moment those prop didn’t get the data they expected, your error log will let you know that you either passed the wrong thing or didn’t pass the prop that had to be passed, which makes it easier to locate errors, especially if you’re writing a lot of reusable components. PropTypes and defaultProps also make these components more self-documenting.

Note:

Unlike proptypes built in earlier versions of React, Proptypes are no longer built in React, and you must add them as dependencies to your project separately. Click on the NPM documentation for prop-Types to learn more.


Know when you need to write new components

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} />
            <My Downloads 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

In the above code I have a component called Profile. There are other components in this component, such as MyOrder and MyDownloads. Now I can write all of these components inline here, because I’m just pulling data from the same place (user) and transforming all of these smaller components into one giant component.

While there aren’t any hard and fast rules about when to move code into components, you need to ask yourself: * Is your code functionality becoming clunky? * Does it only represent its own thing? * Does your code need to be reused?

If the answer to any of these questions is yes, then you need to move the code into the component.

Keep in mind that no one wants to see a huge 200-300 line component in your code.


Component vs PureComponent vs stateless component

It’s important for React developers to know when to use Component, PureComponent, and stateless function components in their code.

You may have noticed in the code snippet above that INSTEAD of declaring the Profile as Component, I called it PureComponent.

First, let’s look at stateless function components.

Stateless function components

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 function components are one of the most common component types in your Arsenal. They give us a neat way to create a component that doesn’t use any state, refs, and lifecycle methods.

The idea of a stateless function component is that it has no state, just a function. So the most important thing is that you define the component as a constant function that returns some data.

In short, a stateless function component is simply a function that returns JSX.

PureComponents

Normally, when a component gets a new prop, React will re-render the component. Sometimes, though, a component gets some new prop that hasn’t really changed yet, but React still triggers a rerender.

Using PureComponent will help you prevent this unnecessary re-rendering. If prop is a string or a Boolean, PureComponent will recognize it when it changes. But PureComponent will not trigger rerendering if a property in the object changes.

So how do you know when React triggers unnecessary re-renders? You can check out this amazing React package called Why You Update. This package notifies you in the console when potentially unnecessary rerendering occurs.

Once unnecessary re-rendering is identified, you can use PureComponent instead of Component to prevent unnecessary re-rendering.


Use bits to organize, share, and reuse components

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

You can use Bit to organize your team’s components in a shared collection and make them shared by team members, using her real-time playground, individual tests, and more to make your shared components more usable.

By isolating and sharing components, you can speed up application development and team development while reducing duplicate code. It’s OSS, and OSS is free, so feel free to try it out.


Use React Dev Tools

If you really want to become a professional React Developer, you should already be using React Dev Tools regularly during development.

If you use React, you probably need React Dev Tools.

React Dev Tools works with all major browsers, such as Chrome and Firefox.

React Dev Tools gives you access to the entire structure of your React application and allows you to see all the states and props used in your application.

React Dev Tools is a great way to explore the React component and help diagnose any problems in your application.


Use inline conditional statements

This tip can be a bit controversial, but I find that using inline conditional statements makes my React code a lot cleaner.

Take a look at this code:

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

In the code above, isRole is a basic function that checks if an individual is “affiliate” and then has a component called
.

What are the benefits of writing this:

  • I don’t have to write a separate function.
  • I don’t need to write another “if” statement in my render function.
  • I don’t need to create a “link” anywhere else in the component.

Writing inline conditional statements is simple. The conditional statement is written first, and if the result of the conditional statement is true, the component renders the
component.

Next, we link this conditional statement with
using &&. This way, the component is rendered only if the conditional statement returns true.


Use Snippet Libraries whenever possible

Open the Code editor (I use VS Code) and create a.js file. When you type rc, in this file you should see the following:

Hit Enter and you will immediately get this:

The beauty of these snippets is that they can potentially help you not only avoid bugs, but also identify the latest and greatest syntax.

You can install many different snippets of code in the code editor. The one I use with VS Code is called ES7 React/Redux/react-native/JS Snippets.


React Internals- Understand how React works

React Internals explains the basics of React in five parts and ultimately helps me become a better React Developer!

React Internals will help you understand when and how to do the right thing in React if you encounter problems that you may not fully understand, or if you want to understand how React works.

This is especially useful for people who have ideas but don’t know where to execute code. Understanding the basics of how React works will help you become a better React developer.


Quickly review

  • Linting: Use ESLint, Airbnb’s JavaScript style guide, or ESLint’s React plugin.
  • Use propTypes and defaultProps.
  • Know when you need to write new components.
  • Know when to write Components, pureComponents, and stateless components.
  • Use React Dev Tools.
  • Use inline conditional statements in your code.
  • Using Snippet Libraries saves a lot of time wasted on boilerplate code.
  • Learn how React works with React Internals.
  • Use tools such as Bit/StoryBook to improve component development workflows