5 Pro Tips That Will Make You a Better React Developer

5 Pro Tips That Will Make You a Better React Developer

Β·

5 min read

Hey Developers πŸ‘‹!

I'll provide some Pro React tips in today's blog to help you become more proficient with React. Some of them may be familiar to you, but a few will be very special to you.

Let’s start with the first one!

1. Better Imports πŸ’Ž

In a React app or any JavaScript/TypeScript project, you will have a messy folder structure and a lot of imports.

Let's assume you have a folder structure like this in your project

image.png

This is how your imports will look like

image.png

And it's gonna be even worse if you are importing in a file that is nested deeply.

image.png

To solve this, you can add a jsconfig.json (or tsconfig.json if you have a TypeScript project) and then add the following to it.

{
    "baseUrl": ".",
    "paths": {
        "@/*": ["./*"]
    }
}

This configuration will now essentially allow you to import folders like @/components, @/utils or @/hooks etc from anywhere in the codebase.

Now your imports will look like this

image.png

2. Clean forms 🧑

Usually, in React, we use controlled inputs and that makes the code very messy.

This is what the code in a form with controlled input looks like.

image.png

Instead, what you can do is set the name prop on the <input /> and then later you can get the value for all inputs using the FormData class.

This is how the code will look now

const HomePage = () => {  
    const handleSubmit = e => {
        e.preventDefault()
        // Create FormData and convert it to an object
        const form = new FormData(e.target)
        const formData = Object.fromEntries(form.entries())
        // Or use destructuring 
        const { firstName, lastName } = Object.fromEntries(form.entries())
        // API and backend call
    }

      return (
        <div>
            <form onSubmit={handleSubmit}>
                <input name="firstName" />
                <input name="lastName" />
                <button type="submit">Submit</button>
            </form>
        </div>
    )
}

And the state is gone 😎

disappear

In this version, the code looks much cleaner and more readable compared to that version using controlled inputs with the state.

Essentially what is happening here is that we create a new instance of FormData class, and we convert it to an object using Object.fromEntries() and pass in the form.entries() inside it.

Which in turn returns to us an object with the "name" of the input and the value is the text input by the user.

If you want to get even better handling than this, consider using a form library like react-hook-form, formik or any alternatives. Thanks to Mohamed Moulay for suggesting this

3. Use Vite ⚑

A lot of people use Create React App when building their React projects. Let me tell you there is a better alternative to Create React App.

You might have noticed the problems with the speed of Create React App. It takes a lot of time to create the project, takes a lot of time to start the project as well.

fast

Enter Vite

Vite is a super powerful tool that lets you create Vanilla, React, Preact, Vue, Svelte and Lit projects with TypeScript support 🀯!

Vite is a lot faster than Create React App. Here's a video by Jesse Hall that shows how fast Vite is compared to CRA.

At the time this video was made, Vite had @vitejs/app command but now it has changed to just vite

To generate a Vite project, you just need to execute this command and then select the appropriate choices.

npm create vite
# or
npm init vite

4. Stretchy Props ❗

Have you ever seen something similar in your React app?

image.png

There are numerous props to send in and also, and the names of the props and their values are the same here. It becomes difficult to write all of it down.

A better way to pass in these props without repeating these names is like this

image.png

Here, you create an object with the properties you need to pass in called props and then while returning the component, you spread the object to pass everything in. This makes the code developer-friendly.

5. SWR - A better way to fetch data πŸ’ͺ

If you have done any sort of data fetching and displaying in a React app, you know how much work you have to do to make it better for the end user.

Usually, this is how you fetch data in a React app

image.png

With this "normal" way of data fetching, the user experience isn't that good

Instead, if we use swr, that will make everything better because

  1. No state management
  2. No loading state management
  3. Refetch anytime
  4. Caching and much more...

mind blowing

The first step is to install the swr library through NPM or the package manager of your choice

npm i swr

Once it's installed, go ahead and change your code to use SWR this way.

import useSWR from 'swr';

const fetcher = (url) => fetch(url).then((r) => r.json());

export default function App() {
  const { data, error } = useSWR(
    'https://jsonplaceholder.typicode.com/photos',
    fetcher
  );

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;
  return <p>{data[0].id}</p>;
}

One of the most killing features of SWR is that every time the window is focused, it refetches and updates the data in the background to get up-to-date data.

With that, you can also trigger the refetch manually using the mutate function.

import useSWR from 'swr';

const fetcher = (url) => fetch(url).then((r) => r.json());

export default function App() {
  const { data, error, mutate } = useSWR(
    'https://jsonplaceholder.typicode.com/photos',
    fetcher
  );

  const fetchAgain = () => {
    mutate();
  };

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;
  return (
    <div>
      <button onClick={fetchAgain}>Refetch</button>
      <p>{data[0].id}</p>
    </div>
  );
}

Read more about SWR here

If you want more control over your data fetching, mutations and caching, React Query/Tanstack Query might be better for you instead of SWR

Β