How To Write Better Code In React

April 18, 2018 0 Comments

How To Write Better Code In React

 

 

React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.

In this post, I will show you a few tips that will help you become a better React Developer. I will cover a range of things from tooling to actual code style, which can help you improve your skill with React. 💪

One thing that’s really important for writing better code is good linting. Because if we have a good set of linting rules set up, your code editor will be able to catch anything that could potentially cause a problem in your code.

But more than just catching problems, your ES Lint setup will constantly make you aware of React best practices.

Take the code snippet above. Say you want to reference a new property called this.props.hello in your render() function. Your linter will immediately go red and say:

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

Linting will help you be aware of the best practices in React and shape your understanding of the code. Soon, you will start to avoid making mistakes when you write your code.

You can either head over to ESLint and set up a linting utility for JavaScript, or you can use Airbnb’s JavaScript Style Guide. You can also install the React ESLint Package.

In the earlier section, I talked about how my linter acted up when I tried to pass an unvalidated prop.

Here, if we say that the userIsLoaded is not required, then we would need to add this to our code:

static defaultProps = {
userIsLoaded: false,
}

So anytime we have a PropType that’s used in our component, we need to set a propType for it. As in, we need to tell React that userIsLoaded is always going to be a boolean value.

And again if we say that userIsLoaded is not required then we’re going to need to have a default prop. If it is required, then we don’t have to define a default prop for it. However, the rule also states that you shouldn’t have an ambiguous propTypes like object or array.

This is why we are using shape to validate user, which has another an id inside it, which has a propType of string, and the entire user object is required.

Making sure you have your propTypes and defaultProps set up on every single component that uses props will go a long way.

The moment those props don’t get the data that they are expecting, your error log will let you know that you are either passing in something incorrectly or something that is expecting it is not there, making error finding just way easier especially if you are writing a lot of reusable components. It also makes them a little bit more self-documenting.

Unlike earlier versions of React, proptypes are no longer included inside React and you will have to add them separately to your project as a dependency.

Click here to know more:

Here I have a component called Profile. I have other components like MyOrder and MyDownloads inside this component. Now I could have written all these components inline here since I am just pulling the data from the same place (user), Turning all these smaller components into a one giant component.

While there aren’t any hard and fast rules on when to move your code into a component, ask yourself:

  • Is your code’s functionality becoming unwieldy?
  • Does it represent its own thing?
  • Are you going to reuse your code?

If any of these question’s answer is yes, then you need to move your code into a component.

Keep in mind that the last thing anyone wants to see in your code is a giant 200–300 line component full of crazy bells and whistles.

It is very important for a React developer to know when to use a Component, PureComponent, and a Stateless Functional Component in your code.

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

First, let’s check out a stateless functional component.

Stateless functional components are one of the most common types of components in your arsenal. They provide us with a nice and concise way to create components that are not using any kind of state, refs, or lifecycle methods.

The idea with a stateless functional component is that it is state-less and just a function. So what’s great about this is that you are defining your component as a constant function that returns some data.

In simple words, stateless functional components are just functions that returns JSX.

Usually, when a component gets a new prop into it, React will re-render that component. But sometimes, a component gets new props that haven’t really changed, but React will still trigger a re-render.

Using PureComponent will help you prevent this wasted re-render. For instance, if a prop is a string or boolean and it changes, a PureComponent is going to recognize that, but if a property within an object is changing, a PureComponent is not going to trigger a re-render.

So how will you know when React is triggering an unnecessary re-render? You can check out this amazing React package called Why Did You Update. This package will notify you in the console when a potentially unnecessary re-render occurs.

Once you have recognized an unnecessary re-render, you can use a PureComponent rather than a Component to prevent things from having an unnecessary re-render.

If you are serious about becoming a pro React Developer, then using React Dev Tools should be commonplace practice in your development process.

If you have used React, there is a good chance that your console has yelled at you to use React Dev Tools.

React Dev Tools are available for all major browsers such as Chrome and Firefox.

React Dev Tools give you access to the entire structure of your React app and allow you to see all the props and state that are being used in the app.

React Dev Tools is an excellent way to explore our React components and helps diagnose any issues in your app.

This opinion might ruffle a few feathers but I have found that using Inline-Conditional Statements considerably cleans up my React code.

Take a look at this code snippet:

Here I have a basic function called that checks if a person is an “affiliate”, followed by a component called <MyAffiliateInfo/>.

What’s great about this is that:

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

Writing inline-conditional statements is quite simple. You begin by writing you conditional statement. You could say true and it will always show the <MyAffiliateInfo /> component.

Next we link this conditional statement with <MyAffiliateInfo /> using &&. This way, the component will only be rendered when the conditional statement returns true.

Open up a code editor (I use VS Code), and create a .js file.

Inside this file when you type rc, you will see something like this:

Hitting enter, you will instantly get this:

What’s great about these code snippets is that not only do they help you potentially save bugs but they also help you identify the latest and greatest syntax.

There are many different snippet libraries that can be installed in your code editor. The one I use for VS Code is called ES7 React/Redux/React-Native/JS Snippets.

React Internals is a five-part series that helped me understand the very basics of React, and eventually helped me become a better React Developer!

If you are having issues with something that you might not have understood fully, or if you understand how React works, then React Internals will help you understand the When and How to do things right in React.

This is especially helpful to those who have an idea but don’t quite know where to execute their code.

Understanding the basics of how React works will help you become a better React developer.


Tag cloud