Best Ways to write Code in ReactJS

In this article, we will be focusing on some best practices to write code in ReactJS, to make the codes more readable and user-friendly. We have to keep in mind that writing code takes effort. But to make it organized and readable takes more than just effort. But doing some simple things while coding in React components will make it better.

Following are the best ways to write reactJS code

  • One file, One component
  • Using Functional Component
  • Custom ReactJS hook
  • Less code inside JSX

Declarative way to write code in ReactJS

ReactJS uses a declarative approach for building Components. In the end, the User Interface is all about HTML, CSS, and JavaScript. And we combine HTML, CSS, and JavaScript to make these Components. After that, we combine all of these components together to create the entire User Interface. But to make a Component, CSS is the least important here. Though, to make the User Interface eye pleasant, CSS is a must.

So basically we have to be focused on HTML and JavaScript for creating and managing Components. But we do can add CSS  but it is not the focus of ReactJS.

ReactJS allows us to manage reusable and reactive Components that consist of HTML and JavaScript. And for the declarative approach, what it means is, that with ReactJS we don’t necessarily have to tell ReactJS that a certain HTML element should be created, updated, or inserted in a specific place on the User Interface. We do this with vanilla JavaScript.

Instead, with ReactJS, we define the desired target state depending on different or similar conditions and let ReactJS figure out the actual JavaScript and DOM (Document Object Model). This means, we will define some states and targets, and the ReactJS will figure out what to show or do on the actual web page.

We just define, the end states and under which conditions which state should ReactJS use these states. And ReactJS will do the rest, which makes it easier to develop the front-end application.

So we could say in the end, we built custom HTML Elements and combine them together to build a User Interface.

Things to remember while writing RectJS Codes

We can not actually write codes however we want in ReactJS. To increase readability and maintain scalable codes we have to follow some basic things.

1. One file for One Component

To code in ReactJS, we can write all the Components in one file. But it will reduce the readability of our codes and it will make the codes most likely unmanageable. So it is a good practice to create individual files for each Component.

// folder structure for Home.js
// src/components/Home.js

import React from 'react';

const Home = () => {
    return (
        <div>
            <h1>This is Home Page</h1>
        </div>
    );
};

export default Home;

As we can see in the above code snippet, we have created a separate file for Home.js Component and exported it to use in another Component. By doing it, we don’t have to handle all the JavaScript codes inside of a single file rather we can easily manage and locate which file should we manipulate to take an effect on User Interface.

// Folder structure for Navbar Component
// src/components/Navbar.js

import React from 'react';

const Navbar = () => {
    return (
        <div>
            //menu options
            <ul>
               <li>Home</li>
               <li>About</li>
               <li>Blogs</li>
            </ul>
        </div>
    );
};

export default Navbar;

For another example, we can take a look at the above code, where we have created another file just to manage Navbar.js Component.

2. Use Functional Component

There are two types of Components in ReactJS that we can work with. Class Component and Functional Component. ReactJS comes with many React Hooks. Such as, useState(), useEffect(), useRef() etc. We can build a Functional Component just like we declare vanilla JavaScript Functions. Instead of regular function declaration, we will use es6’s Arrow Function to create a Component. Though we can use the regular function for that as well.

// folder structure for Home.js
// src/components/Home.js

import React from 'react';

// creating functional component with arrow function
const Home = () => {
    return (
        <div>
            <h2>Functional Components</h2>
        </div>
    );
};


export default Home;
// folder structure for Home.js
// src/components/Home.js

import React from 'react';

// creating functional component with regular function

function Home(){
    return (
        <div>
            <h2>Functional Components</h2>
        </div>
    );
};

export default Home;

3. Custom ReactJS hook

While creating a User Interface sometimes we might need to share some data with different Components. What will we do then?  Do we have to write the same code twice for each Component?

Actually, No. That’s when Custom Hooks come in handy. We can write the codes that we will share with multiple Components in a separate file. And it is a good practice to name the file as useData.js . For example, if we want to get some product data from an API that needs to be shared with multiple Components, we can name the hook as useProducts.js .

// folder structure for useProducts.js
// src/hooks/useProducts.js

import React from 'react';

const useProducts = () => {
    // declaring the state that will hold the products as an array, comming from API

    const [products, setProducts] = useState([]);

    // as the API is not a internal property of React it is a side effect. hence we use useEffect() hook to handleside effects
    useEffect(() => {
        fetch('https://fakestoreapi.com/products')
            .then(res => res.json())
            .then(data => setProducts(data))
    }, []);

    // returning the products so that we can call this custom hook from any other Component and use the products
    return { products };
};
// exporting this hook so that it can be imported from anywhere (other components)
export default useProducts;

Here, we have created a custom hook that gets all the products from an API, and from the function, we are returning products so that we can destructure the products while using this custom hook.

// folder structure for Home.js
// src/components/Home.js

import React from 'react';
import useProducts from '../src/hooks/useProducts'
// destructuring the products array from the useProducts() custom hook.
const {products} = useProducts();
const Home = () => {
    return (
        <div>
            <h2>Total Products: {products.length}</h2>
        </div>
    );
};

export default Home;

If we look above code snippet we can see, that we are now in our Home.js Component and we have imported custom hook useProducts() from its file location. After importing we destructure the products and we are using them inside the <div>...</div> tag. In the same way, we can import this custom hook from any other Component and use the data of this custom hook.

4. Use less JavaScript inside JSX

As we know, Components in ReactJS are created with HTML Elements, CSS and JavaScript. But to make the code more clean and readable we should try to avoid implementing JavaScript codes inside JSX (which is basically a markup coating for increasing code readability) as much as possible. For example, we can take a look at below code snippet,

// folder structure for Home.js
// src/components/Home.js

import React from 'react';

const Home = () => {
    return (
        <div>
            {/* declaring and using the onClick function inside JSX. If the Componet gets larger and larger, the readability of codes reducecs proportionally because of it*/}
            <h2 onClick={e => alert(e.target, 'is clicked')}>JavaScript in JSX</h2>
        </div>
    );
};

export default Home;

If we look at the above code snippet, we have declared the onClick function inside JSX which seems OKAY for now. But if we add more codes, means more JSX elements; things can get a little messier. Which decreases the readability of code. Instead of doing that, we can just declare the onClick function outside of JSX and then just call the function. It will make the code more simple and easy to read.

// folder structure for Home.js
// src/components/Home.js

import React from 'react';

const Home = () => {
    // declaring the function outside of JSX, makes the code more readable
    const clickedFunction = e =>{
        alert(e.target, 'is clicked')
    };

    return (
        <div>
            <h2 onClick={clickedFunction}>JavaScript in JSX</h2>
        </div>
    );
};

export default Home;

Just like this.

These are the basics that we have to keep in mind while writing codes in ReactJS. If we maintain the Components in the right way, the codes can be more manageable and we can get the best out of them.