10 tips how to make your ReactJS code like a PRO

Michal Jurkowski
9 min readApr 25, 2018

Many of us, frontend developers, js developers and also react developers work in the teams that include developers with different skills level. The best method to improve our code is GOOD QUALITY CODE REVIEW — but not that we check if all thinks work, but also how did our colleges make this result — so we have to assurance clean code.

Why? That is simple — if your team count up to 5 person, that is easy to ask how it works. But if your team is huge or there are many dynamic changes, that good quality code helps us and another developers to understand it, and of course you can feel like a PRO ;P

I have taken 10 Best practices, that help me and my team to improve quality of code in our React Projects. This tips generally based on ES6 functionality, but we don’t use them always. Look for them, and feel free to use it too!!

1. Class Components VS Function Components

All of us are very happy, that in ES6 was implemented class support — I love it! In react we can make a component by extending simple class called ‘React.Component’. There we have simple state management methods, components events support etc. Sometimes it is too much that we need, but we know that we can use it.

import React, { Component } from 'react'class MyComponent extends Component {
render() {
return <p>Hello {this.props.text}</p>
}
}

But in react development many developers forget how we can make a component simply using functional component, that could be a function with one parameter — props.

import React from 'react'const MyComponent = (props) => <p>Hello {props.text}</p>

But the usage of this two components looks the same!

<MyComponent text="World"/>

Okay — so why I should use functional components? Because there are much lighter then extended class. Remember that we use React and another reactive framework because we think about memory usage — this frameworks make a virtual DOM without unnecessary props and methods to manage them easier, faster and to reserve less memory. So if we think about optimisation, we need to think about this difference.

Okay — so when we could use Class Components and when Functional Component? The rules is very easy — WHEN YOU NEED USE SOMETHING THAT FUNCTIONAL COMPONENT DOESN’T HAVE — USE CLASS COMPONENT!

Quite easy? Yeah! Start to write you components from sketch like functional component. When you see that you need to use something like states or detect some changes in your component — like componentWillMount() etc. Then you could transform it to Class Component.

When you think about this which type of component use, the you become to be like a PRO!

2. “If” statements in component template

Look below… Do you know what’s wrong with this method of if statement?

{ a > b ? <MyComponent/> : null }

If condition is inconsistent the React will render null . Hmm… it’s okay — I don’t see the so there is no problem… NOT!!!

This null still exist in your DOM, so if you want to take all children from you list or call for nth-children then this null will be counted!!!

Solution?

{ a > b && <MyComponent/> }

So easy, so elegant. Like a PRO!

3. Function binding

I LOVE ES6! I LOVE ARROW FUNCTIONS!!! But if you understand how they really works, then usage of them in react is much easy. More about them (Here). In very short — arrow function get a scope from their direct parent, that there was declare.

Why am I talking about that reference to function binding? Because there is very easy trick to make you code cleaner. Standard function binding to event look like that:

class MyComponent extends Component {
constructor(props) {
super(props)
this.clickHander = this.clickHander.bind(this)
}
clickHander(e) {
e.preventDefault();
alert('Hello ' + this.props.text)
}
render() {
return <buttom onClick={this.clickHander}></button>
}
}

We declare clickHandler function, but the main context of them( this ) is the button that we click. So if we want to bind this as our class, then, we need to bind it in constructor .

Can I make it easier? OF COURSE!!! By arrow function because it get a scope from their direct parent, that there was declare (copy from above).

class MyComponent extends Component {
clickHander = (e) => {
alert('Hello ' + this.props.text)
}
render() {
return <buttom onClick={this.clickHander}></button>
}
}

Easier, faster and looks like a PRO!!!!

** IMPORTANT **

If you want to use this structure — remember that right now it is in experimential, so we need to translate it by babel using transform-class-property , which is standard in create-react-app . Reference here

4. Shorter props and states

Another thing that we can use from ES6, but we forgot — destructuring. In many code reviews we can see that huge objects are destructured for small parts.

...
var width = this.props.myObject.width,
height = this.props.myObject.height,
color = this.props.myObject.color;
...

That is too long, and not flexible solution. There is very easy way to destructure that smarter.

...
var { width, height, color } = this.props.myObject;
...

Quite easy when we want to have variable with the same name like key of object.

How we can use it in react?

import React, { Component } from 'react'class MyComponent extends Component {
render() {
let { name, age } = this.props
return <p>My name is {name}. I'm {age} years old.</p>
}
}

or with function component

import React from 'react'const MyComponent = ({ name, age }) => <p>My name is {name}. I'm {age} years old.</p>

Another example? When you use big structure of props or states.

import React, { Component } from 'react'class MyComponent extends Component {
state = {
team: [
{
person: {
basicInfo: {
name: 'Michal',
age: 27
}
}
}
]
}
render() {
let { name, age } = this.props.team[0].person.basicInfo

return <p>My name is {name}. I'm {age} years old.</p>
}
}

Easy? Easy! And looks like a PRO ;)

5. Styles separation

Very quick advice — SEPARATE STYLES!!! :D

But we have two situation:

  1. We can use external styles from files(.css, .scss)
  2. We use some components that use their building styles, but they use inlines only like material-ui

First situation is quite easy, put to webpack sass and style loader, and that’s all!

But second situation is a little difficult, and I want to show you few solutions:

#1. Const with styles

import React, { Component } from 'react'const styles = {
paragraph: {
'fontSize':'10px',
'color':'#ff0000'
}
}
class MyComponent extends Component {
render() {
return (
<div>
<p style={styles.paragraph}>This is my first text</p>
<p>This is my second text</p>
</div>
)
}
}

#2. CSS Modules

It’s nice idea to load CSS like object and reference in your code to class that exist in you css file.

import React, { Component } from 'react'
import classes from './style.css'
class MyComponent extends Component {
render() {
return (
<div>
<p className={classes.paragraph}>This is my first text</p>
<p>This is my second text</p>
</div>
)
}
}

Quick video how to prepare you webpack for CSS

And remember — if you can separate you files and make it easy to edit, then you work like a PRO!

6. Environments dependencies

We love to prototype something, but we did’t want to put something for production version. How to hide your fragments or available something only for developers or on development mode?

Use ENVIRONMENTS VARIABLES — extra variable which you can assign during starting or building you project. When you are starting any action from terminal, then you can put extra variables that are pushed to app by node in process.env then you can push anything.

ex. MY_VARIABLE="Hello World!" npm run start

Then in process.env.MY_VARIABLE we should see our value.

If you are using create-react-app then you’ve got builded variable like NODE_ENV that return mode of your build like development , production or test . And that all for basic usage.

const isDebug = process.env.NODE_ENV === 'development'

How to use it in practice?

import React, { Component } from 'react'const isDebug = process.env.NODE_ENV === 'development'class MyComponent extends Component {
render() {
return (
<div>
<p>This is my public text</p>
{ isDebug && <p>This is my development text</p> }
</div>
)
}
}

I’m not sure is it’s like a PRO but you can pass by ENV VARIABLE some environment sensitive informations like API root url, or you project address etc.

** Important **

Don’t forgot that if anybody want to decode you source code, then he can see you dependencies.

7. Remember about possibilities to component testing

That is quite easy to understand — if you think about testing you react application, then probably you want to use Jest for testing. But you need to remember that if you connect your components with some backend like Apollo(for GraphQL) or state machine like Redux or another HOC then you need to remember that this extensions will not available in simple component testing. And that’s normal. When you want to test your SINGLE component, then you are testing only there functionality — checking if input props and actions on component works properly.

So how to prepare your components to testing?

If you don’t have any HOC, export normally:

import React, { Component } from 'react'class MyComponent extends Component {
render() {
let { name, age } = this.props
return <p>My name is {name}. I'm {age} years old.</p>
}
}
export default MyComponent

but if you want to use any HOC use this pattern:

import React, { Component } from 'react'export class MyComponent extends Component {
render() {
let { name, age } = this.props
return <p>My name is {name}. I'm {age} years old.</p>
}
}
export default myHocFunction(MyComponent)

Why? Because when you want to import in other document you component with HOC then you use:

import MyComponent from './components/MyComponent'

but in tests you can use

import { MyComponent } from './components/MyComponent'

Simple code, simple solution but many possibilities to usage — because of course we are a PROs ;)

8. Use helpers

Very, very simple and important thing. Sometimes you use the same functions or you got the same rules in many components. It is unnecessary to duplicate you code. Just separate helpers functions to other file and put it in global helper directory:

public
src
helpers
globals.js
modules
Users
helpers
index.js
UserList.js
User.js
app.js

** Important **
If you duplicate your code — you should improve it!

File separation is the best way to become like a PRO!

9. React Fragments

You have prepared your best layout, HTML markup is the best one, every think looks pretty… ARHHHH AMAZING, just react implementation… header… looks perfect… jumbotron… awesome… wait… I’ve got one section that is not wrapped… OH NO… react… SHIT!

That was a problem when you want to make a component that didn’t have a wrapper. For long time we need to wrap everything:

class MyComponent extends Component {
render() {
return (
<div>
<p>This is my first text</p>
<p>This is my second text</p>
</div>
)
}
}

because react didn’t allow us to put it alone. why — was not use if each element inside have own uniq key, that it can recognise which part of DOM is his component.

BUT React has added new feature called “React Fragments”, that allow you to build component that group many element without wrapping in the DOM. It works the same like div wrapping but instead div we use <React.Fragment></React.Fragment> statement or short version <></>

Ex.

class MyComponent extends Component {
render() {
return (
<React.Fragment>
<p>This is my first text</p>
<p>This is my second text</p>
</React.Fragment>
)
}
}

or

class MyComponent extends Component {
render() {
return (
<>
<p>This is my first text</p>
<p>This is my second text</p>
</>
)
}
}

Amazing — you you are like a PRO read full article from documentation

10. PROs use Prop Types and Default Props

If you are PRO you think about things that you components needed. Why should I use PropTypes?

During development you can be sure you your other components pass properly value to them. If you want to use string, then in your props should be a string, because ex. you can do inside component specific things for string. Adding defaultProps if your propType is not required protect you that you/or your project college forget to add some prop to component.

import React, { Component } from 'react'
import PropTypes from 'prop-types'
class MyComponent extends Component {
render() {
return <p>Hello {this.props.text.toLocaleUpperCase()}</p>
}
}
MyComponent.propTypes = {
text: PropTypes.string
}
MyComponent.defaultProps = {
text: 'World'
}

And you you want to know more about PropTypes — Full documentation

SUMMARY

As you can see, that 10 tips are very easy to implement to your code. Read it one more time, add reaction if you like it and write in comments if there is something unclear or if you want to read about something more specific! Good luck!

--

--

Responses (1)