DEV Community

Cover image for React js best practices you must know as a developer
Kumar Kalyan for Documatic

Posted on • Updated on

React js best practices you must know as a developer

RShare Draft

Publish

Add Cover

Add Subtitle
Article title…

Write

Preview

Editor Guide

React.js is one of the most popular javascript libraries for building user interfaces and is used by top tech giants like Netflix, Meta, Dropbox, etc. It was developed and maintained by Facebook (now meta) and has huge community support, well-structured documentation, and tons of articles and tutorials over the internet. As per surveys, an average reacts js developer can earn up to a six-figure salary. In this article, I will be explaining some of the key terms and concepts that you must keep in mind before you start working on your next react.js project.

Folder structure

A software project must have a proper and organized folder structure. Let's understand this with a scenario suppose you are debugging a software project not having a proper folder structure and all you need to do is to configure a query in the API used and now you have to surf the whole code base for a single line. A proper folder structure brings the ability to debug and build products faster by 5 times. All you need to do is to keep specific files under proper folders say all the unit tests should be kept under a folder named test, all the global components under a folder named global_components, etc. Check out the folder structure below to get a clear idea.

react folder structure

Destructuring Props

Destructuring props is one of the most important and useful points that you must have in your mind as a react developer. Destructuring has a lot of advantages too like improving code sustainability, and readability, providing developers with the ability to write clean & more optimized code, providing components with exact data properties, saving iteration time of an array having multiple objects, etc.

React component with destructuring


import React from 'react';

const User = props =>{
    // Destructuring Props
    const {id, name} = props;
    return (
        <div>
            <div className="id">
               <li> {id} </li>
            </div>

            <div className="name">
                <h4>{name}</h4>
            </div>
        </div>
        )
  }
export default User;
Enter fullscreen mode Exit fullscreen mode

React components without destructuring


import React from 'react';

const User = props =>{

        return (
        <div>
            <div className="id">
               <li> {props.id} </li>
            </div>

            <div className="name">
                <h4>{props.name}</h4>
            </div>
        </div>
        )
  }
export default User;
Enter fullscreen mode Exit fullscreen mode

Code Refactoring

Comments are nonother than simple English text which makes the code more understandable and readable. Comments enable you to remember which piece of code is written for what purpose. Also, proper comments help to debug code and fix bugs faster. Use tools like better comments, and JS doc for the same.

//assets 
import logo from './logo.svg';
import './App.css';
//hooks
import useState from 'react';
// components 
import Button from './components/Button';

// main function 
function App() {
  //using a hook
  const [hello, setHello] = useState(0);

  // get data from an API  
  const handleFetch = () => {
    fetch("https://www.google.com/search?q=hello").then(data => {
      data.json()
    }).then(t => console.log(t))
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
      {/* Using a component */}
      <Button />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Use react hooks

Hooks are some special functions that enable you to access the react state and component life cycle features in functional components. Using functional components along with hooks can be more implemented than classes. This helps in making the code easy to read, debug and test. This implementation also reduces the amount of code, and coupling factors and provides better performance.

Functional component with hooks

import React, { useState } from 'react';
import './style.css';

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Building the same using Class component

import React from 'react';

class Counter extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0,
    };
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
  }

  increment() {
    this.setState((previousValue) => ({
      count: previousValue.count + 1,
    }));
  }

  decrement() {
    this.setState((previousValue) => ({
      count: previousValue.count - 1,
    }));
  }

  render() {
    return (
      <div>
        <h1>{this.state.count}</h1>
        <button onClick={this.increment}>Increment </button>
        <button onClick={this.decrement}>Decrement </button>
      </div>
    );
  }
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Test your code

Adding unit tests to your react project can help you a lot in building a successful production-level project. Adding end-to-end test cases will help in reducing software maintenance cost, debug code faster, helps you to ship scalable and high-quality products with a better user experience, and a lot more. For React js testing frameworks like Jest, Cypress can be used to write unit tests. sum.js

function sum(a, b) {
  return a + b;
}
module.exports = sum;
Enter fullscreen mode Exit fullscreen mode

sum.test.js

const sum = require('./sum');
//this is a test 
test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
Enter fullscreen mode Exit fullscreen mode

Debug like a pro

Debugging is also one of the most important stages of the software development life cycle. while debugging a react js project your browser becomes your best friend. I would recommend using the Mozilla firebox browser developer edition and extensions like react-dev tools this will help you in debugging like a pro and understand the component lifecycle.

firefox devtools

Code faster with vscode extensions

vs code is one of the most popular, lightweight, and open-source code editors used for react js development. To Increase your react js development faster by 10x use vs code extensions like ESlint, Prettier, JavaScript ES6 snippets, Tabnine, and most importantly React js code snippets. The last extension will help you to define a component just by typing two characters. type ccc will generate

class  extends Component {
    constructor(props) {
        super(props);
    }
    state = {  }
    render() { 
        return (  );
    }
}

export default ;
Enter fullscreen mode Exit fullscreen mode

again typing enf will generate this code

export const functionName = (params) => {};
Enter fullscreen mode Exit fullscreen mode

Points to remember before deployment

Once you are done with the development process like writing code, debugging, and passing unit tests now is the time for the deployment or in other words shipping the app to production. Here are a few things which you must keep in mind.

  • Make sure to use environment variables to hide your production keys and secrets.

  • You must separate the development packages and production packages

  • Add production and deployment scripts properly or else it will cause trouble in the production

  • Configure the .gitignore file properly

  • Format code properly before pushing it to production

  • Make sure you go through your previous commits and changes and for this, you can use tools like gitlens, gitkraken or tower git client

  • Checkout the react deployment docs here

Conclusion

Congrats, we have reached the end. Make sure to use go through these points before you start working on your next react js project. Feel free to reach out with any queries and share this article with your peers. Stay tuned for the next.

Happy Coding :)
eact.js is one of the most popular javascript libraries for building user interfaces and is used by top tech giants like Netflix, Meta, Dropbox, etc. It was developed and maintained by Facebook (now meta) and has huge community support, well-structured documentation, and tons of articles and tutorials over the internet. As per surveys, an average reacts js developer can earn up to a six-figure salary. In this article, I will be explaining some of the key terms and concepts that you must keep in mind before you start working on your next react.js project.

Folder structure

A software project must have a proper and organized folder structure. Let's understand this with a scenario suppose you are debugging a software project not having a proper folder structure and all you need to do is to configure a query in the API used and now you have to surf the whole code base for a single line. A proper folder structure brings the ability to debug and build products faster by 5 times. All you need to do is to keep specific files under proper folders say all the unit tests should be kept under a folder named test, all the global components under a folder named global_components, etc. Check out the folder structure below to get a clear idea.

react folder structure

Props Destructuring

Props destructuring is one of the most important and useful points that you must have in your mind as a react developer. Destructuring has a lot of advantages too like improving code sustainability, and readability, providing developers the ability to write clean & more optimized code, reducing extra component rendering & array iteration, etc.

An example of props destructuring


import React from 'react';

const Test = props =>{
    // Prop Destructuring
    const {id, name} = props;
    return (
        <div>
            <div className="id">
               <li> {id} </li>
            </div>

            <div className="name">
                <h4>{name}</h4>
            </div>
        </div>
        )
  }
export default Test;
Enter fullscreen mode Exit fullscreen mode

Use comments properly

Comments are nonother than simple English text which makes the code more understandable and readable. Comments enable you to remember which piece of code is written for what purpose. Also, proper comments help to debug code and fix bugs faster.

//assets 
import logo from './logo.svg';
import './App.css';
//hooks
import useState from 'react';
// components 
import Button from './components/Button';

// main function 
function App() {
  //using a hook
  const [hello, setHello] = useState(0);

  // get data from an API  
  const handleFetch = () => {
    fetch("https://www.google.com/search?q=hello").then(data => {
      data.json()
    }).then(t => console.log(t))
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
      {/* Using a component */}
      <Button />
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

use proper hooks

Hooks are some special functions that enable you to access the react state and component life cycle features in functional components. This helps in code refactoring and reducing the amount of code. Of course, you definitely don't want to bind every single state using the class-based approach. There are several types of hooks in react that you can use according to your need.

import { useState } from "react";
const Button = () => {
    // I am a hook 
    const [count, setCount] = useState(0)
    return (<h1>I am a  button </h1>)
}
export default Button;
Enter fullscreen mode Exit fullscreen mode

Adding unit tests

Adding unit tests to your react project can help you a lot in building a successful production-level project. Adding end-to-end test cases will help in reducing software maintenance cost, debug code faster, helps you to ship scalable and high-quality products with a better user experience, and a lot more. For React js testing frameworks like Jest, Cypress can be used to write unit tests.
sum.js

function sum(a, b) {
  return a + b;
}
module.exports = sum;
Enter fullscreen mode Exit fullscreen mode

sum.test.js

const sum = require('./sum');
//this is a test 
test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
Enter fullscreen mode Exit fullscreen mode

Debug like a pro

Debugging is also one of the most important stages of the software development life cycle. while debugging a react js project your browser becomes your best friend. I would recommend using the Mozilla firebox browser developer edition and extensions like react-dev tools this will help you in debugging like a pro and understand the component lifecycle.

firefox devtools

Code faster with vscode extensions

vs code is one of the most popular, lightweight, and open-source code editors used for react js development. To Increase your react js development faster by 10x use vs code extensions like ESlint, Prettier, JavaScript ES6 snippets, Tabnine, and most importantly React js code snippets. The last extension will help you to define a component just by typing two characters.

React JS snippets

Points to remember before deployment

Once you are done with the development process like writing code, debugging, and passing unit tests now is the time for the deployment or in other words shipping the app to production. Here are a few things which you must keep in mind.

  • Make sure to use environment variables to hide your production keys and secrets.
  • You must separate the development packages and production packages

  • Add production and deployment scripts properly or else it will cause trouble in the production

  • Configure the .gitignore file properly

  • Make sure you go through your previous commits and changes and for this, you can use tools like gitkrakraren or tower git client

Conclusion

Congrads , we have reached the end. Makesure to use go through thes e points before you start working on your next react js project. Feel free to reachme out for any quries and share this article with your peers. Stay tuned for the next.

Happy Coding :)

Latest comments (1)

Collapse
 
brense profile image
Rense Bakker

Actually the common practice is to keep related things together. What they mean by that is when you have a sidebar component for example, all unit tests and related stylesheet should be in the same folder as that component so other developers wont have to go through your entire code base to search and collect pieces that belong to the same thing.

Also it's common practice to not add clutter in the form of comments that are obvious. Developers are expected to write clean code that reads almost like plain English (by using proper function/variables names for example). If code needs commenting, its often a sign of dirty code. You don't need to explain to a React dev that you imported a hook by adding a comment //hooks they can already tell you imported a hook. The only time you have to use comments is when there's a complicated piece of business logic thats specific to the domain and another dev cannot tell from just the code exactly what that business logic is.