DEV Community

Cover image for 7 Insanely Useful React Libraries For Your Next Project - No BS
Nitin Sharma
Nitin Sharma

Posted on • Originally published at blog.locofy.ai

7 Insanely Useful React Libraries For Your Next Project - No BS

Understanding React is typically the next step for web developers after becoming familiar with JavaScript because of its popularity. Ever since its release in 2013, it has gathered a significant market share & is extensively used by developers all over the world as the most accessible JavaScript library.

In 2021, React surpassed jQuery as the most used web framework, as per a Stackoverflow survey. Because of React's great popularity, several frameworks and libraries have been developed around it such as Next.js and Gatsby.

In a later version of React (16.8), hooks in functional components were added, enabling you to use state and other react capabilities without creating a class. This was a game-changer.

This made it much simpler and painless to develop a certain sort of functionality with the help of various React libraries & custom hooks.

In this post, we’ll be sharing a curated list of useful React libraries.

Let’s get started.

1. Beautiful React Hooks

The majority of React developers prefer hooks to manage the concepts of props, state, context, or lifecycle, not only because it is easier but also because the core React team encourages this practice as well because it makes the code simpler.

This package takes React hooks a step further.

Let’s take an example of storing values in Local Storage with the help of beautiful-react-hooks.

import React, { useCallback } from 'react';
import { Pill, Paragraph, Icon } from 'beautiful-react-ui';
import useLocalStorage from 'beautiful-react-hooks/useLocalStorage';

const NotificationBadgeExample = ({ notifications }) => {
  const [notificationCount, setNotificationCount] = useLocalStorage('demo-notification-count', notifications);

  const clearNotifications = useCallback(() => {
    setNotificationCount(0);
  }, [notificationCount]);

  return (
    <DisplayDemo>
      <Paragraph>Click on the badge to clear from the local storage</Paragraph>
      <Pill color="primary" onClick={clearNotifications}>
        <Icon name="envelope" />
        You've got {notificationCount} new messages
      </Pill>
    </DisplayDemo>
  )
};

<NotificationBadgeExample notifications={100} />
Enter fullscreen mode Exit fullscreen mode

These types of custom, reusable hooks are prebuilt in the Beautiful React Hooks packages to accelerate the development process.

In a nutshell, Beautiful React Hooks are reusable custom hooks designed for developers.

You have various custom hooks at your fingertips, some of them are as follows:

  1. useQueryParam to ease the process of modifying the query string in the URL for the current location.

  2. useInfiniteScroll which takes care of adding the infinite scroll-related events listeners to the defined target

  3. useDarkMode to handle all logic required to add a dark mode toggle to your website

  4. useToggle which provides a quick and safe utility for managing boolean states

2. React Query

Data fetching may not be as simple as most tutorials make it look. You may want to cache the data, refetch it, or share it across different pages and components.

While the industry standard libraries like fetch and Axios are capable of handling straightforward data fetching, the React Query package takes it to a different level.

It allows you to work in conjunction with these libraries as well as provide methods to seamlessly handle pagination, caching, stale data, and other such complex functionality.

It can even double up as a global state manager and replace libraries like Redux in most apps.

Let’s see how it works.

import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'

const queryClient = new QueryClient()

export default function App() {
return (
  <QueryClientProvider client={queryClient}>
    <Example />
  </QueryClientProvider>
)
}


function Example() {
const { isLoading, error, data } = useQuery({
  queryKey: ['repoData'],
  queryFn: () =>
fetch('https://jsonplaceholder.typicode.com/posts/1').then(res =>
      res.json()
    )
})
if (isLoading) return 'Loading...'
if (error) return 'An error has occurred: ' + error.message

return (
  <div>
    <h1>{data.title}</h1>
    <p>{data.body}</p>
  </div>
)
}
Enter fullscreen mode Exit fullscreen mode

As you can see, we can use our favorite libraries to fetch data inside the queryFn function and we get a host of useful variables and functions such as “error” and “loading” to handle the data.

3. React Hook Form

Have you previously worked with form data and found it complicated? Building a form requires a laborious process of accepting form input, offering validation, handling errors, and submitting a form.

This is where the React Hook Form comes in. It helps you to create forms that are performant, flexible, and extensive, with simple validation.

Consider the following example.

import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

export default function Form() {
 const { register, errors, handleSubmit } = useForm();
 const onSubmit = (data) => {
   console.log("RESULT", data);
   alert(JSON.stringify(data));
 };
 console.log(errors);

 return (
   <form onSubmit={handleSubmit(onSubmit)}>
     <label>First name</label>
     <input
       type="text"
       {...register("First name", { required: true, maxLength: 80 })}
     />
     <label>Last name</label>
     <input
       type="text"
       {...register("Last name", { required: true, maxLength: 100 })}
     />
     <label>Email</label>
     <input
       type="text"
       {...register("Email", {
         required: true,
         pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
       })}
     />
     <input type="submit" />
   </form>
 );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Form />, rootElement);
Enter fullscreen mode Exit fullscreen mode

In this code, we're destructuring the “register”, “errors”, and “handleSubmit” props and using them within our form. This makes handling different form states a piece of cake.

We can define various constraints and patterns to easily validate the user input as well. In our sample code snippet above, we have used constraints like “maxLength: 80” i.e the first name should be no more than 80 characters long as well as a regular expression to test the email provided by the user.

4. Date-fns

As the name suggests, this library makes working with dates easy & it's very lightweight as well with a build size of just 300 bytes.

It provides the most comprehensive yet consistent set of functions to easily handle & manipulate JavaScript dates.

In the code below, you can see how easy it is to format dates.

import { format, formatDistance, formatRelative, subDays } from 'date-fns'

format(new Date(), "'Today is a' eeee")
//=> "Today is a Wednesday"

formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true })
//=> "3 days ago"

formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."
Enter fullscreen mode Exit fullscreen mode

There's also support for internationalization, which makes it an all-rounder package when it comes to working with dates.

import { formatRelative, subDays } from 'date-fns'
import { es, ru } from 'date-fns/locale'

formatRelative(subDays(new Date(), 3), new Date(), { locale: es })
//=> "el viernes pasado a las 19:26"

formatRelative(subDays(new Date(), 3), new Date(), { locale: ru })
//=> "в прошлую пятницу в 19:26"
Enter fullscreen mode Exit fullscreen mode

Moreover, it relies on the native Date type and provides a set of utility functions around it with support for modular imports, so you only import what you need.

5. Recharts

Admin panels, charts, and diagrams provide large sets of information in a visual way to the end users. From showing engagements to website analytics, they have become the de facto standard for visualizing large sets of data.

However, there is no simple way we can create them using HTML and CSS. Creating a few charts, for example, might take multiple hours to get right.

That’s where Recharts will help you.

Line and scatter charts as well as treemaps are just some of the charts & representations that can be easily made with this package.

You need to install it inside your project using the following command.

npm install recharts
Enter fullscreen mode Exit fullscreen mode

The package provides a wide variety of charts you can import inside your project to customize and use them.

import {
 BarChart,
 Bar,
 XAxis,
 YAxis,
 CartesianGrid,
 Tooltip,
 Legend
} from "recharts";

const data = [
 {
   name: "Express",
   usage: 23
 },
 {
   name: "React",
   usage: 40
 },
 {
   name: "Angular",
   usage: 22
 },
 {
   name: "Vue",
   usage: 18
 },
 {
   name: ".NET Core",
   usage: 18
 },
 {
   name: "jQuery",
   usage: 34
 }
];

export default function App() {
 return (
   <BarChart
     width={500}
     height={300}
     data={data}
     margin={{
       top: 5,
       right: 30,
       left: 20,
       bottom: 5
     }}
   >
     <CartesianGrid strokeDasharray="3 3" />
     <XAxis dataKey="name" />
     <YAxis />
     <Tooltip />
     <Legend />
     <Bar dataKey="usage" fill="#8884d8" />
   </BarChart>
 );
}
Enter fullscreen mode Exit fullscreen mode

Here is the output for the code.

Rechart Output

6. Styled Components

JavaScript and React have a large developer community, and the team often adds new features.

For instance, in ES6, a new feature called template literal is introduced, which allows you to design custom string interpolation rules. In layman's terms, this template literal along with CSS can be used to create Styled Components.

Consider the following example:

Install the Styled Components package from npm or yarn within your react app.

npm install styled-components
Enter fullscreen mode Exit fullscreen mode

Import into your file.

import styled from 'styled-components
Enter fullscreen mode Exit fullscreen mode

Now you can define several Styled Components.

const Button = styled.button`
  border-radius: 1px;
  border: 2px solid black;
  color: black;
  margin: 0.5em 1em;
  padding: 0.25em 1em;
`;

const Container = styled.div`
  background-color: grey;
  text-align: center;
`

<Container>
  <Button>Click Me</Button>
</Container>
Enter fullscreen mode Exit fullscreen mode

Simply said, Styled Components allow you to create reusable custom HTML elements with defined CSS characteristics and apply them anywhere you want inside your app.

7. Dnd Kit

All the top apps these days have the ability to drag and drop various components from one part to another.

The Dnd Kit does just that. It enables you to add drag and drop events to your components as well as provides various presets such as Sortable to handle lists, trees, and other such specific use cases.

You must first install the package before you can use it.

npm install @dnd-kit/core
Enter fullscreen mode Exit fullscreen mode

You can then use it within your react app.

Here are a few examples to get you going.

This package is incredibly powerful not just for creating simple drag and drop but also for building gaming interfaces as shown below:

Card_Image

Is it OK to Rely on Third-Party Packages?

We've seen a lot of react packages in this post, and they're all useful in making web development easier and faster.

Modern websites require polished animations, a diverse set of features as well as compatibility with different browsers. These packages help you offload some of these functionalities to them and usually, they have a very low learning curve as well making them easier to plug into your projects.

You may use more React packages like React Responsive, Apollo Client, Formik, and Zustand, among others, and they will all be very helpful to you however one thing to keep in mind is that these packages can drastically increase your bundle size as well as slow down the performance of your website if over-used.

Therefore, it is always a good practice to remove the packages you don’t need & only import the parts of the packages that you’ll be using wherever possible.

Another time-tested practice is to divide your React app into smaller, manageable components which promote reusability and easier long-term maintenance. This is where Locofy.ai can help.

With the Locofy.ai plugin for Figma and Adobe XD, you can export your designs into production-ready, highly extensible React code and what’s more, is that you can even split your code into components that accept props.

This makes it easier to manage them and you can safely import packages only inside the components that require it, improving the overall performance & maintenance.

Hope you like it.

That's it--thanks.

Top comments (0)