Go Back

React Best Practices Every Developer Have to Follow in 2022

React Best Practices
Posted by
Technostacks
Dec 1 2021

ReactJS serves as a universally accepted and well-known platform when it comes to frontend frameworks. However, React Js is useful to 60 percent of the developers, so there is a need to learn about the best strategies.

ReactJS is a supple open-source JavaScript library utilized to build exceptional applications. In this article, you will highlight the insights and react best practices to help React Js developers and businesses create great and high-performing applications.

List of React Js Best Practices to Follow in the Year 2022

  1. Create a new base react application structure
    While creating a react project, there is a need to define a scalable project structure which is important for the best react practices for a robust project. It is possible to use the NPM command ‘create-react-app.’ React folder structure differs based on project specification and complexity. You will get the availability of the various React Js best practices considered while defining project architecture:
    First of all, there is a need for the Folder Layout.The React folder structure architecture focuses on reusable components to share the design pattern among multiple internal projects. The idea of component-centric file structure implies that all the components’ files (like test, CSS, JavaScript, assets, etc.) must fall under a single folder.

    Components
    |
    --Login
    |
    --tests--
    --Login.test.js
    --Login.jsx
    --Login.scss
    --LoginAPI.js

    Also, there is another approach to grouping the file types.

    APIs
    |
    --LoginAPI
    --ProfileAPI
    --UserAPI
    
    Components
    |
    --Login.jsx
    --Login.test.js
    --Profile.jsx
    --Profile.test.js
    --User.jsx

    Also, there is a possibility for nesting them based on requirements.

  2. CSS in JS
    When it comes to large projects, one of the most fundamental of the React best practices is styling and theming. However, it turns out to be a challenging task like maintaining those big CSS files. So, this is where the CSS-in-JS solutions came into the picture.Among numerous libraries, you can use the needed one based on the requirement, like some for the complicated themes.
  3. Children Props
    Across precise JSX expressions with an opening and a closing tag, the content amid these tags gets conceded as a distinct prop: props.children. It serves as a part of the React documentation and props.children works as the special prop, automatically passed to every component. The goal is to render the content included between the opening and closing tags when invoking a component.Also, it finds use in the rendering method of the content of one component inside another component. That said, there is a possibility to pass functions as child props. Stack Overflow’s 2020 Developer Survey suggests that from 57.378 replies, 68.9% of responses showed interest in enduring engagement with React JS.
  4. Reusability principle in React
    Reusable components of the react developer serve as the piece of UI used in various parts of an application that can help build more than the UI instance. Also, you can get the button component displayed with different colors in several parts of the application. Therefore, reusability is important, and this is why there is a need to create new components to the minimum required. Rule of one function = one component, improve the reusability of components. Skip is trying to build a new component for a function when you see that there is a component for that function. Reusing components across your project not only achieves consistency but also contributes to the community. Read More:- Best React Component Libraries for 2021-2022In case you notice that any component becomes huge and difficult to maintain, break it up into as many smaller components. For example, create a Button component that can handle icons. You should ensure that making it more modular to cover many cases with the same piece of code. Make sure that the components should be abstract enough but not overly complex. Here is an example:

    class IconButton extends React.Component {
      [...]
      render() {
        return (
          <button onClick={this.props.onClick()}>
            <i class={this.props.iconClass}></i>
          </button>
        );
      }
    }
  5. Consolidation of duplicate code
    Consolidation of duplicated code serves as one of the react js best practices. A common rule for all code is keeping it brief and concise. The best way to avoid duplication is following Don’t Repeat Yourself (DRY). Achieve the objective by scrutinizing the code for patterns and similarities. With that, you will get the scope to eliminate duplication. Rewriting can make it more concise.Also, this condition is largely dependent on the reusability principle in React. Also, if you wish to add multiple buttons that contain icons, as an alternative to adding the markup for each button, use the Icon Button component. Also, go further by mapping everything into an array.

    const buttons = ['facebook', 'twitter', 'youtube'];
     
    return (
      <div>
        {
          buttons.map( (button) => {
            return (
              <IconButton
                onClick={doStuff( button )}
                iconClass={button}
              />
            );
          } )
        }
      </div>
    );
    
  6. Higher-Order Components (HOC)
    Consideration of higher-order components as one of the best practices for Reactjs developers. Higher-Order Components serve as an advanced technique in React, allowing reuse of the component logic inside the render method. When considering the advanced level, transform a component into a higher order of the component. For example, show some components when the user stays logged in and complement the similar code with every component.
  7. Stop relying on class-based components
    The best practice to follow for your React application is to Stop relying on class-based components. React will allow writing your components as class-based components. This is the major reason why the Java/C# developers lean toward writing classes.However, class-based components have an issue in the form that they start becoming complex and harder for you and your teammates to understand. In addition to that, these components are less abstract. The introduction of React hooks has become a boon for the developers as they are no longer required to write classes. Including useState, useEffect, and use context can assist you in the objective.
  8. Embracing the useState hook
    Usually, there is a need for the class-based components to maintain the state. However, this condition is no longer true with useState. React components are immutable in general as there are associations with the performance metrics. In this regard, it can be said that the useState hook provides the best scope to re-render a component after changing a variable.

    import { useState } from ‘react’;
    export function Foo() {
        const [ someData, setSomeData ] = useState(“”);
        return (
        <>
            <p>{ someData }</p>
            <button onClick={() => setSomeData(Math.random())}>Go</button>
       </>
    }
    

    The above code shows that setSomeData serves as a function that will re-draw this component after assigning the someData variable. Thus, when the user clicks on <button>, there will be a need for putting in some random number in someData and then redraw.

  9. Naming the component after the functionNaming the component is considered as the best react practices and it should bear the potential to convey instantly what the component does. Naming the component based on the need for the code confuses you at a future point. Name a component Avatar that finds use anywhere.It will be highly favorable for authors, users, or in comments. So, let us spot the difference. AuthorAvatar can also be used in the context of its usage. But, in this case, the issue will be that it can limit the utility of that component. Naming a component after the function will turn out to be useful to the community.
  10. Using capitals for component names
    Using JSX (a JavaScript extension) means that the names of the components need to begin with uppercase letters. Let us take an example here. You can choose to name components as SelectButton instead of the select button. This is essential as it gives an easy path to the JSX to identify them differently from default HTML tags.Earlier React versions used to have a list of all built-in names to differentiate them from custom names. The limitation, in that case, was, however, that it needed constant updating. If you see that JSX is not your language, you can use lowercase letters. But the problem still stays the same. It comes with loads of difficulty in the reusability of components.
  11. Minding the other naming conventions
    When working with React, the developers are generally using JSX (JavaScript Extension) files. The general rule states that any component you create for React must be used in the Pascal case or upper camel case. For example, in case you wish to create a function that submits a form, name it SubmitForm in the upper camel case. The goal here is to not use submitForm, submit_form, or submit_form. The upper camel case turns out to be the commonly used Pascal case.
  12. Consideration of the separate stateful aspects from rendering
    Components in React have two forms-stateful or stateless. Stateful components play the role of storing information about the component’s state and providing the necessary context. The condition is the reverse in the case of stateless components. They have no memory and cannot give context to other parts of the UI.The general rule is that they can just receive props (inputs) from the parent component and return u JSX elements. Such components become scalable and reusable, and similar to the pure function in JavaScript. One of ways to cater React best practices is possessing the stateful data-loading logic distinct from the versioning stateless logic. The best move, in this case, is that you can have one stateful component to load data and another stateless component that can help in displaying the data. The motto is the reduction of the complexity of the components.
  13. Default XSS protection with data binding
    Default XSS protection with data binding serves as a react best practices and Security standards. When learning more about the react architecture best practices, it’s worth noting that you do not forget to use the default data link with braces. In this case, React automatically evades values to protect you from XSS attacks. However, you can get this protection standard only when rendering.
    Also, make sure that you use JSX data-binding syntax {} to place data in your elements.

    {data}

    is one of the prime examples. Also, note that you avoid dynamic attribute values without custom validation.

  14. Keeping a note of the Dangerous URLs
    URLs contain dynamic script content via javascript: protocol URLs. Make sure that you use validation to assure your links are http: or https: that can help avoid javascript: URL-based script injection. Achieve URL validation with the utilization of the native URL parsing function. The next role you need to play is to match the parsed protocol property to an allow list. Here is an example:

    function validateURL(url) {
      const parsed = new URL(url)
      return ['https:', 'http:'].includes(parsed.protocol)
    }
     
    <a href={validateURL(url) ? url : ''}>Click here!</a>
    
  15. Rendering HTML
    React JS security is improving with the utilization of the proper principles. Insert HTML directly into rendered DOM nodes with the use of the dangerouslySetInnerHTML. However, note that the content inserted this way must undergo sanitization beforehand.To make things better, the best move is to utilize a sanitization library like dompurify on any of the values prior to placing them into the dangerouslySetInnerHTML prop. Also, you can use dompurify when inserting HTML into the DOM:

    import purify from "dompurify";
    <div dangerouslySetInnerHTML={{ __html:purify.sanitize(data) }} />
  16. Utilisation of the tools like Bit
    One of React best practices helping to organize all your React components is tools like Bit. The motto behind using these tools is to maintain and reuse code. In addition to that, these tools also help code to become discoverable and promote team collaboration in building components.
  17. Use of snippet libraries
    Code snippets help keep up with the best and most recent syntax. The goal is also to keep your code relatively bug-free. That said, this practice serves as one of the React best practices that you should not miss out on.Many snippet libraries are already there that you can use, like, ES7 React, Redux, JS Snippets. Using snippet libraries is needed as the React architecture best practices also involve using code snippets. The use of code snippets makes it easy for you to keep up with the latest syntax. The best part is that the snippet libraries keep the code relatively bug-free.
  18. Writing tests for all code
    When it comes to the implementation of any programming language, adequate testing is needed. The goal is to ensure that the new code added to your project integrates with the existing code. There are chances of breaking existing functionality. Writing tests for all codes can eradicate the issue. Create a _Test_ directory within the directory to conduct relevant tests.Divide tests in React into testing the functionality of components and tests on the application once it renders in the browser. Use cross-browser testing tools that can help with the objective of testing the latter category. For the former, use a JavaScript test runner, Jest, to help to emulate the HTML DOM using jsdom to test React components.A completely accurate test is only possible in a browser that has been long associated with the real device. Also, it can be said that Jest provides a good approximation of the real testing environment that can assist a developer a lot in the development phase of the project. Also, this principle serves as React practical advice for improving code quality.
  19. Using Map Function for Dynamic Rendering of Arrays
    The best way to get the expected results is to create an object with props that return a dynamic HTML block. You can do so without the need for writing repeated code. React provides a map() function that can serve as the best tool to display arrays in order. Using an array with a map() is one of the best ideas. Also, you can use one parameter from the array as a key.

    render () {
      let cartoons = [ "Pika", "Squi", "Bulb", "Char" ];
      return (
      <ul>
        {cartoons.map(name => <li key={name}>{name}</li>)}
      </ul>
      );
    }
    

    In addition to this, ES6 spread functions can send a whole list of parameters in an object by using Object.keys().

    render () {
      let cartoons = {
      "Pika": {
        type: "Electric",
        level: 10
      },
      "Squi": {
        type: "Water",
        level: 10
      },
      "Bulb": {
        type: "Grass",
        level: 10
      },
      "Char": {
        type: "Fire",
        level: 10
      }
      };
      return (
      <ul>
        {Object.keys(cartoons).map(name => <Cartoons key={name} {... cartoon[name]} />)}
      </ul>
      );
    }
    
  20. Keeping state business logic separate from UI
    Separate the state management logic from the UI logic that can help you in multiple ways. Components that do both are not impactful as they make them less reusable, more difficult to test, and difficult to refactor, especially when you’re looking for state management. Rather than writing the logic for placement of the state inside a component, the best move is to extract it into a hook of its own.
  21. Embracing wishful thinking
    A helpful technique to the program is the consideration of wishful thinking. There is a particular method that you need to follow for it. First of all, send an API request to fetch the users at the stage the component mounts. The next step is to show a placeholder until you’re getting a response back from the server.As soon as you get the response back, make sure that you show the list of the users. You wish here serves as the component called Fetch and is completely responsible for doing an API call. Also, it is associated with the list of query parameters. API call pending means that there is a need to show a placeholder.So, there is a need to pass a component called Placeholder that specifies how it appears. Once the API call finishes, automatically a component will be rendered. Keep building on top of the logic, adding more props to the Fetch component to specify pagination, sorting, filters.
  22. The implementation of the Object-oriented React
    React is all regarding functional programming. The introduction of hooks references the strong desire to shift away from components written as classes. The objective here is to enter the functional world. Functional programming is easy to reason about, and in addition to this objective, testing becomes easy. Try different techniques and notice how much they make sense.Create classes for the data that can assist you in the long run. For example, instead of json data, create a class like so: new Group(groupJsonDataFromApi). With that, also you can expect some added functionality.With that, you can also easily note the class for the Post entity and class for the Group entity. Also, the shared fields are prevalent, namely id and permissions. The best way to foster convenience is to also add getters for each class. The idea here is to test whether the authenticated user can delete a certain entity.
  23. Learning the benefits of testing and doing it from the start
    Writing automation tests comes with complexity in that, at a certain point, it’s impossible to test React projects manually without spending time and resources. When starting the project, it’s easy to justify skipping writing test code codebase in that circumstance becomes relatively small.However, when it comes to more than fifty components and multiple higher-order components, testing projects manually take a whole day. Writing test code serves the objective of making your code more modular. In addition to that, it also helps you find errors faster and safeguard against crashing. Automation testing helps grow projects when manual testing fails to verify the code.

Key Takeaways

Building React applications at scale usually seems to be a complicated task that requires you to consider the best decision for the web developers. Best practice in React turns out to be the one that is associated with the users and your team.

The best tip is to experiment with tools and methods for scaling React projects. With that, it will be easier for you to go ahead with the react coding.

X