Coding Tips

React JS Tips and Tricks 2021

Here are some pretty obvious and not complicated in use trends and best practices in React.

It's been a long time since the first release of the React.

Before we will dive deeper into react’ itself, let’s do a small throwback into react’s history.

History

React was created by Jordan Walke in 20, a software engineer at Facebook, who released an early prototype called "FaxJS". Jordan was influenced by XHP, an HTML component library for PHP development. React was first deployed on Facebook's News Feed in 2011 and later on Instagram in 2012. And finally, it was open-sourced at JSConf US in May 2013. Today, we are going to take a look at the React tips and best practices you can apply in your work.

Game changer

The past decade was definitely a golden time for web developers.

Since 2006 jQuery development has been the most popular way to add interactivity and animations to web browsers. Making websites with jQuery was radically different from what we know now.

AngularJS, the first web framework maintained mainly by Google to build SPAs (Single Page Applications), was released later in 2010.

AngularJS development offers two architectures to handle web projects: MVC (Model-view-controller) MVVM (Model–view–viewmodel). As a web framework, it generally allows developers a lot of great approaches and tools (e.g. two-way data-binding) to build web applications.

Ten years ago AngularJS was a 100% game changer in web development. But as this industry is moving forward at a fast pace, new technologies come up and offer new approaches. The same is about React.

React exposed a brand new paradigm for how to develop a SPA. It offered a few really awesome approaches which I personally like very much.

To put it in a nutshell, I was a huge fan of the Component paradigm and the way to split all of your application into different reusable components.
But JSX syntax really blew my mind as it allows us to generate HTML with pure JavaScript without any .html files which I personally hated. Which is exactly why I want to share with you guys what React is, tips and tricks on how you can get the most out of it, and how you can use those tips for better React performance.

Top 1 React feature

For the last 7 years React offered a lot of cool features, and one of the reasons for such huge success of the react library in my opinion is that React developers built a really huge and strong community and supported this technology all the time, providing different features and improvements. The community has a huge impact on your overall experience, and one of the best React tips and tricks I can offer is always turning to the community for advice and help. There are tons of component building tips React community can share, so do not be afraid to ask. 

All this topic is based on my personal opinion and 100% subjective but I really think that the best React feature ever is Hooks.

Hooks

Hooks were a new addition for React 16.8 and the idea behind this feature was very simple: they let you use state and other React features without writing a class.

I’ll remind you that you always had two options on how to make your components in the react

Option #1 is to make class components.

Option #2 is to make function components.

But all react developers always knew such terms as Smart Components and Dumb Components.

Dumb Components

Dumb components are also called ‘presentational’ components because their only responsibility is to present something to the DOM.

Smart Components

Smart components (or container components) are responsible to handle the state of the application and care about how the app works.

Dream

Developers of React are pretty often saying that they prefer to make as many functional components in the application as possible, and the idea behind this wish is very simple.

Functional components usually are smaller, they look and read easier.

Dreams come true

Hooks allow us to do literally the same things as class components such as handle the local state of the component and listening for different component’s life cycles, but with the functional components, which will require much fewer lines of the code.

Let’s take a look at very simple samples of both approaches just to compare their simplicity.

Class component

import React, { Component } from "react";

export class TestComponent extends Component {
  constructor(props) {
    super(props);
    state = {
      user: {},
    };
  }

  componentDIdMount() {
    // do some stuff after component rendered
    // set user data
  }

  componentWillUnmount() {
    // do some stuff before component will be removed from the DOM
  }

  render() {
    const { firstName, lastName } = this.state.user;

    return (
      <div>
        First Name: {firstName}
        Last Name: {lastName}
      </div>
    );
  }
}

Functional component

import React, { useState, useEffect } from "react";

export const TestComponent = () => {
  const [user, setUser] = {};

  useEffect(() => {
    // do some stuff after component rendered
    // set user data
    return () => {
      // do some stuff before component will be removed from the DOM
    };
  }, []);

  return (
    <div>
      First Name: {user.firstName}
      Last Name: {user.lastName}
    </div>
  );
};

Conclusion

As you can see this is a very easy and minimalistic sample and even here we can see that the class component is bigger, and you have to do a lot of additional steps to do the same things as in the functional component.

But usually, we have much more complexity in our containers which will turn our class component into a giant for a couple of hundreds of lines of the code which would be so painful to read to our teammates from the team. 

Functional components in their turn make the code look cleaner and easier to read. Which is why using the functional components is one of the advanced React tips I would share. 

Hooks Advantages

1. hooks are easier to work with and to test (as separated functions from React components*) and make the code look cleaner, easier to read — a related logic can be tightly coupled in a custom hook.

2. code that uses hooks is more readable and has less LOC (lines of code) what we already saw in the example above.

3. thanks to hooks it’s easy to make code more reusable/composable (also they don’t create another element in DOM like HOCs do) — with HOCs we are separating unrelated state logic into different functions and injecting them into the main component as props, although, with Hooks, we can solve this just like HOCs but without a wrapper hell.

4. you can define several separated lifecycle methods instead of having all in one method (so you can split componentDidMount logic with ease). Compare examples below:

5. hooks are going to work better with future React optimizations (like ahead of time compilation and components folding) — components folding might be possible in future (https://github.com/facebook/react/issues/7323) — what means dead code elimination at compile time (less JS code to download, less to execute)

6. even now, the minification of functions in JavaScript is much better than the minification of JavaScript classes. It’s not possible for example to minify method names of JS classes as every method can be either private or public, so we don’t know when it’s used outside the class. Less code to download, process, and execute has a positive impact on the end-user.

Last but not least

When you are following functional components and hooks patterns there are some additional benefits that are opening to you.

It is a very common issue when we have a big application that interacts with a lot of different data, and we need to use all this data across the app and our components, usually in cases like this we are facing an issue that bears the name Prop Drilling.

It becomes so painful when you have to pass some new props from the container level to some child components and you have to literally walk through the 9 circles of hell.

One of the best React performance tips I can give you here is using functional components. Functional components are able to solve this problem very easily by using a Context.

Let’s take a look at a small example:

Prop Drilling example

const App  = () => {
  // some logic
  return <Toolbar theme="dark" />;
}

function Toolbar(props) {
  // The Toolbar component must take an extra "theme" prop
  // and pass it to the ThemedButton. This can become painful
  // if every single button in the app needs to know the theme
  // because it would have to be passed through all components.
  return (
    <div>
      <ThemedButton theme={props.theme} />
    </div>
  );
}

const ThemedButton = () => {
  // some logic
  return <Button theme={this.props.theme} />;
}

Context Example

// Context lets us pass a value deep into the component tree
// without explicitly threading it through every component.
// Create a context for the current theme (with "light" as the default).
const ThemeContext = React.createContext('light');
const App = () => {
    // Use a Provider to pass the current theme to the tree below.
    // Any component can read it, no matter how deep it is.
    // In this example, we're passing "dark" as the current value.
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
}

// A component in the middle doesn't have to
// pass the theme down explicitly anymore.
function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

const ThemedButton = () => {
  // Assign a contextType to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  // In this example, the current theme is "dark".
  static contextType = ThemeContext;
  return <Button theme={this.context} />;
}

Reducer

But still, if we need to use a reducer we can easily do this using useReducer hook

The most useful react hooks

To be honest, it is a too deep topic to discuss but if to summarize everything that has been said, I would note few hooks which will allow you to use the pattern I described in this topic:

1. useState - will allow you to manage the local state of your component

2. useEffect - is a very powerful hook that allows you to handle different lifecycles of the app such as (componentDidMount, componentWillUnmount, shouldComponentUpdate, etc.) 

3. useContext - will help you to interact with the contexts

4. useReducer - will allow you to work with your store on the Containers level

Best Practices

In general, at the end of this topic, we can definitely see some trends and best practices in the react, they all are pretty obvious and not complicated in use, but unfortunately not all react developers so far are using them.

My list of the best practices for react would look like this:

1. Write small and re-usable functional components that would be looking cleaner and easier to read

2. Use hooks as a strong addition for the first item from the list, and to build more reusable code to not repeat yourself

3. Avoid prop-drilling in the app which will simplify a lot your and your teammate's job.

4. When you write a code, always think about your team and people who will probably work with this code later.

I agree that this list can be longer, there are so many options we can add to this list, but in my opinion, these items will guarantee you and your team an easier, faster, and non-painful developer experience of your projects. I find these React tips for 2021 developers to be quite useful. I hope you now have a better understanding what React is and tips you can use to make working with it more rewarding. 

avatar
Front-End Developer
JavaScript Developer with 6 years of extensive experience in web, mobile, backend using such technologies as React, AngularJS, Cordova, ReactNative, NodeJS. Was working on different projects such as mobile development, fin-tech, cloud platform, media streaming platform and in the different teams starts from small 2 pizza team startups to big corporations with a few hundreds of people. More than 3 years primarily working on React and related technologies.