DEV Community

Cover image for 5 npm packages for React to Increase your Productivity
Varshith V Hegde
Varshith V Hegde

Posted on

5 npm packages for React to Increase your Productivity

React has revolutionized the way we build user interfaces, making it easier and more efficient to create dynamic and interactive web applications. With its component-based architecture and virtual DOM, React has quickly become a cornerstone of modern web development. However, as applications grow in complexity, developers often find themselves seeking tools and resources to boost their productivity and streamline their workflows.

Enter NPM packages – the lifeblood of the JavaScript ecosystem. These packages offer a wealth of pre-built functionalities that can drastically accelerate your development process. In this blog post, we'll explore seven NPM packages that are tailor-made for React developers. These packages are not only popular among the community but can also become your secret weapons for crafting cleaner code, improving performance, and ultimately, delivering exceptional user experiences.

From state management and routing to styling and testing, this curated list covers a range of aspects in modern React development. Whether you're a seasoned React veteran or just stepping into the realm of frontend development, these packages are sure to empower you to create more efficient, feature-rich, and maintainable React applications.

So, let's dive into the world of NPM packages that can supercharge your React projects and propel your development journey to new heights.

List of the npm packages

  1. Formik
  2. ZOD
  3. TanStack Query
  4. ShadCN
  5. Axios

Formik

Formik is famous open-source library for managing forms in React Applications . Let's face it , forms are really verbose in React. To make matters worse, most form helpers do wayyyy too much magic and often have a significant performance cost associated with them. Formik is a small library that helps you with the 3 most annoying parts:

  • Getting values in and out of form state
  • Validation and error messages
  • Handling form submission
  • It provides Field Components
  • Also Form Lifecycle

Formik will keep things organized--making testing, refactoring, and reasoning about your forms a breeze.
To install Formik in your React.js project, you can use npm or yarn, the two most popular package managers for JavaScript projects. Open your terminal and navigate to your project directory. Then, run one of the following commands:

Using npm

npm install formik
Enter fullscreen mode Exit fullscreen mode

Using Yarn

yarn add formik
Enter fullscreen mode Exit fullscreen mode

Using Formik in React Application simple example

import React from 'react';
import { Formik, Form, Field } from 'formik';

const SimpleForm = () => {
  const handleSubmit = (values) => {
    console.log(values);
  };

  return (
    <div>
      <h1>Simple Form using Formik</h1>
      <Formik initialValues={{ name: '' }} onSubmit={handleSubmit}>
        <Form>
          <div>
            <label htmlFor="name">Name</label>
            <Field type="text" id="name" name="name" />
          </div>
          <button type="submit">Submit</button>
        </Form>
      </Formik>
    </div>
  );
};

export default SimpleForm;
Enter fullscreen mode Exit fullscreen mode

For further usage you can visit Formik Docs

ZOD

If you are using Typescript in your React application them this might be a go to tool for you to use . Remember how even when you mention users to use some format or use only string or numbers in the forms then they mess it up . Now using ZOD you can specify the schema of forms for checking the types and it will handle it all.

Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple string to a complex nested object.

Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures.

And the good news is that it also integrable with Formik.

Installing ZOD :

npm install zod       # npm
yarn add zod          #yarn
Enter fullscreen mode Exit fullscreen mode

Basic Usage of Zod :

import React, { useState } from 'react';
import { z } from 'zod';

// Define a schema for user data
const userSchema = z.object({
  name: z.string().min(3),
  age: z.number().min(18),
});

const UserForm: React.FC = () => {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = () => {
    try {
      const userData = userSchema.parse({ name, age: parseInt(age) });
      console.log('User data:', userData);
      setError('');
    } catch (error) {
      setError(error.message);
    }
  };

  return (
    <div>
      <h1>User Form with Zod Validation</h1>
      <div>
        <label>Name:</label>
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      </div>
      <div>
        <label>Age:</label>
        <input type="number" value={age} onChange={(e) => setAge(e.target.value)} />
      </div>
      <button onClick={handleSubmit}>Submit</button>
      {error && <p style={{ color: 'red' }}>{error}</p>}
    </div>
  );
};

export default UserForm;
Enter fullscreen mode Exit fullscreen mode

For Further Usage visit ZOD Docs

TanStack Query (React Query)

We know that in react we use fetch to call the api's and everything . And it is difficult to manage it .
TanStack Query (FKA React Query) is often described as the missing data-fetching library for web applications, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your web applications a breeze.

React Query is hands down one of the best libraries for managing server state. It works amazingly well out-of-the-box, with zero-config, and can be customized to your liking as your application grows.

React Query allows you to defeat and overcome the tricky challenges and hurdles of server state and control your app data before it starts to control you.

Installing the React Query :

npm i @tanstack/react-query     #npm
pnpm add @tanstack/react-query  #pnpm
yarn add @tanstack/react-query  #yarn
Enter fullscreen mode Exit fullscreen mode

Basic Usage of it :

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://api.github.com/repos/TanStack/query').then(
        (res) => res.json(),
      ),
  })

  if (isLoading) return 'Loading...'

  if (error) return 'An error has occurred: ' + error.message

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <strong>👀 {data.subscribers_count}</strong>{' '}
      <strong>✨ {data.stargazers_count}</strong>{' '}
      <strong>🍴 {data.forks_count}</strong>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

For More Usage visit TanStack Query Docs

Shadcn/UI

ShadCN UI is a library for building user interfaces in React.js applications. It provides a set of components and tools that can help you create well-designed and accessible forms in your web applications. The library is specifically tailored to streamline the process of building forms, which are commonly used but can be complex to implement correctly.
It provides Re-usable components built using Radix UI and Tailwind CSS. This is NOT a component library. It's a collection of re-usable components that you can copy and paste into your apps.

Installing Shadcn :

npm i shadcn-ui
Enter fullscreen mode Exit fullscreen mode

Basic Usage of Shadcn Ui :

import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion"

export function AccordionDemo() {
  return (
    <Accordion type="single" collapsible className="w-full">
      <AccordionItem value="item-1">
        <AccordionTrigger>Is it accessible?</AccordionTrigger>
        <AccordionContent>
          Yes. It adheres to the WAI-ARIA design pattern.
        </AccordionContent>
      </AccordionItem>
      <AccordionItem value="item-2">
        <AccordionTrigger>Is it styled?</AccordionTrigger>
        <AccordionContent>
          Yes. It comes with default styles that matches the other
          components&apos; aesthetic.
        </AccordionContent>
      </AccordionItem>
      <AccordionItem value="item-3">
        <AccordionTrigger>Is it animated?</AccordionTrigger>
        <AccordionContent>
          Yes. It&apos;s animated by default, but you can disable it if you
          prefer.
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  )
}
Enter fullscreen mode Exit fullscreen mode

Above example is just one usecase for more such example visit Shadcn docs

Axios

You may be struggling to use fetch and async and manage the data api calling . To make it easy i bring to you te axios library which provides wide options for api management.

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.

Features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Query parameters serialization with support for nested entries
  • Automatic request body serialization to:
    • JSON (application/json)
    • Multipart / FormData (multipart/form-data)
    • URL encoded form (application/x-www-form-urlencoded)
  • Client side support for protecting against XSRF

Installing Axios :

npm install axios   #npm
yarn add axios      #yarn
Enter fullscreen mode Exit fullscreen mode

Basic Usage of Axios in React Application :

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    // Make an HTTP GET request using Axios
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

For Further Information Visit Axios Docs

Honourable Mentions

  • Redux(Redux is a predictable state container for JavaScript apps.)
  • React Spring(React Spring is a library for building interactive, data-driven, and animated UI components.)

Conclusion

These may be some of the package that i used , and there are tons of them . If you find any packages intresenting or provide detailed usage of it just comment it down .

Innovate, iterate, and integrate these tools into your toolkit, and watch your productivity skyrocket as you build exceptional React applications that stand out in today's competitive digital landscape.

Happy coding 🚀 and may your React endeavors be ever more productive and creative!

Stay curious, keep coding, and let these packages transform your React world.

Connect with me

Top comments (4)

Collapse
 
suponova profile image
Super Jeo

Awesome one!!

Collapse
 
varshithvhegde profile image
Varshith V Hegde

Thank You🙌

Collapse
 
nextupweb profile image
nextupweb

Usefull

Collapse
 
varshithvhegde profile image
Varshith V Hegde

Thank You🙌