An in-depth guide to choosing the perfect NPM package.

React is a JavaScript library for building user interfaces. It is not only a front-end UI development framework, but also a complete front-end development ecosystem.

React doesn’t have all the solutions, but you can find NPM packages for different scenarios from the thriving ecosystem to address development issues.

Today, we look at the following 16 latitudes to find the best solution.

1. Global status management

Sharing state between components is mandatory in 99% of applications, and there are some good local and external solutions.

recommended

If you ask me for a solution, I will say Redux, not because it is the best, but because it is the most practical. Many companies already use it, which means you have to use it at some point, too.

  • redux-toolkit + react-redux

We used to use Redux, usually referring to the Redux + React Redux combination, but now we have a simpler solution: Redux Toolkit + React Redux, which helps us avoid three common problems with Redux:

  1. “Configuring a Redux store is too complicated.”

  2. “I have to add a lot of packages to get Redux to do anything useful.”

  3. “Redux needs too much boilerplate code”

The Redux Toolkit simplifies the process of writing Redux logic and setting up a store, allowing us to write shorter logic that is easier to read while still following the same Redux behavior and data flow.

Install React-Toolkit
$ npm install @reduxjs/toolkit --save
# or 
$ yarn add @reduxjs/toolkit

It can also be installed using the scaffolding redux template (method 2)
# Redux + Plain JS template
$ npx create-react-app my-app --template redux

# Redux + TypeScript template
$ npx create-react-app my-app --template redux-typescript
Copy the code

Sample code:

import { createSlice, configureStore } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter'.initialState: {
    value: 0
  },
  reducers: {
    incremented: state= > {
      state.value += 1
    },
    decremented: state= > {
      state.value -= 1}}})export const { incremented, decremented } = counterSlice.actions

const store = configureStore({
  reducer: counterSlice.reducer
})

store.subscribe(() = > console.log(store.getState()))
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}
Copy the code

If you’re still using the Redux + React Redux combination, the Redux community also provides a lot of middleware to simplify scenarios.

  1. Redux-thunk – Used to handle asynchronous actions (used with redux);

  2. Redux-persist – for storing data locally (offline support);

  3. Reselect – for faster query storage;

$ npm install redux react-redux redux-thunk redux-persist reselect --save
Copy the code

An alternative to

  • Context – Built-in with React, which is good for simple use and bad for performance, especially if you have a lot of changing data.
  • Recoil – Designed to solve specific problems, now or experimental status, accurate update, next generation status management solutions.
  • jotai- Minimalist API, no string keys, typescript-oriented, andreact-springBoth belong to Poimandres.
  • Mobx – Observer based, reactive programming is recommended for small to medium sized projects.

2. Manage server status

If your application relies heavily on some external data source, managing that data (caching, updates, and so on) is critical to performance.

recommended

  • react-query- applies toreact hooksRequest library.

React Query will help you get, synchronize, update, and cache your remote data. It provides two simple hooks for adding, deleting, changing, and querying data.

It handles caching stale data and more out of the box. It is simple, powerful and configurable.

# installation
$ npm i react-query --save
# or
$ yarn add react-query
Copy the code

Basic Features overview:

  1. Transport/protocol/back-end agnostic data fetch (REST, GraphQL, Promise, etc.);

  2. Auto cache + refetch (revalidation upon expiration, window refocus, polling/live);

  3. Parallel + dependent query;

  4. Mutation + requery of reaction formula;

  5. Multi-layer cache + automatic garbage collection;

  6. Paging + cursor based query;

  7. Load more + infinite scroll query/scroll recovery;

  8. Request cancellation;

  9. React Suspense + Fetch- as-you-render;

  10. Dedicated Devtools.

Simple example (global configuration) :

// main.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

import { QueryClient, QueryClientProvider } from 'react-query'

const queryClient = new QueryClient()

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>
  document.getElementById('root')
)
Copy the code
// QueryExample.jsx
import React from 'react'
import { useQuery } from 'react-query'
import { ReactQueryDevtools } from 'react-query/devtools'

function QueryExample() {
  const { isLoading, error, data, isFetching } = useQuery('repoData', () =>
    fetch('https://api.github.com/repos/tannerlinsley/react-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>{isFetching ? 'Updating...' : ''}</div>
      <ReactQueryDevtools initialIsOpen /> 
    </div>
  )
}
export default QueryExample
Copy the code

An alternative to

There is also a library similar to React Query.

  • swr

The name “SWR” comes from stale-while-revalidate: an HTTP cache invalidation policy popularized by HTTP RFC 5861. This strategy first returns data from the cache (expired), sends a FETCH request (revalidation), and finally gets the latest data.

The main benefit of this library is that it was built by Vercel, the people who created next.js. Therefore, you can expect better performance when working with next.js.

# installation
$ npm i swr --save
# or
$ yarn add swr
Copy the code

SWR covers all aspects of performance correctness and stability to help you build a better experience:

  • Fast page navigation
  • The polling interval
  • Data dependencies
  • Revalidate when focusing
  • Verify again when the network is restored
  • Local cache updates (Optimistic UI)
  • Intelligent error retry
  • Paging and scrolling positions restored
  • React Suspense
  • .

3. The scaffolding

Creating React applications from scratch is complex, and setting up WebPack, Babel, and so on can be daunting.

recommended

  • Create-react-app – Official scaffolding tool.

It wraps WebPack and Babel together into a new scripting tool called React-Scripts to manage the entire application.

Create the React project
$ npx create-react-app my-app
# or
$ npm init react-app my-app
# or 
$ yarn create react-app my-app
Copy the code

  • Vite – Use native ESM files, no packaging, next generation front-end development and build tool.

Vite makes full use of the “native capabilities of the operating system”, shortening the link, eliminating the complex packaging steps, avoiding a lot of performance problems in the construction, Vite has the significance of “cross-era”.

At the moment, the Vite ecosystem is not as prosperous as Webpack, but over time, Vite will definitely replace Webpack.

Create the React project
# npm 6.x
$ npm init vite@latest my-react-app --template react 

# NPM 7+ requires additional double lines:
$ npm init vite@latest my-react-app -- --template react

# yarn
$ yarn create vite my-react-app --template react
Copy the code
  • Next. Js – A framework for building React applications.

Out of the box, next.js provides server-side rendering, static site generation, serverless functionality, and more.

It is a toolkit whose most important feature is out-of-the-box SEO support, giving you everything you need to create high-performance Web applications.

Create next.js
$ npx create-next-app my-next-app
# or
$ yarn create next-app my-next-app
Copy the code

Next. Js is built around the concept of pages. A page is a React component that is exported from a.js,.jsx,.ts, or.tsx file in the pages directory.

A page is associated with a route based on its file name. For example, pages/about.js is mapped to /about. You can even add dynamic routing parameters to the file name.

An alternative to

If you’re starting to build some basic projects with React, you have other options.

  • Gatsby – Build a static content oriented website, not suitable for other projects.

4. UI component library

A universal and complete UI library not only helps us solve repetitive application scenarios, but also saves development costs and ensures the performance of the library after being tempered by the community.

recommended

  • Antd – comprehensive documentation, mature design system, rich ecology, Chinese first choice.

Antd is a React UI component library based on Ant Design system, which is mainly used to develop enterprise-level middle and back-end products.

# installation
$ yarn add antd
# or
$ npm i antd --save

# Umi based building project
$ yarn create @umijs/umi-app
# or 
$ npx @umijs/create-umi-app
Copy the code
  • Blueprint – a React based Web UI toolkit.

Developed in TypeScript and Scss, Blueprint is powerful and has its own color and typography specifications, which are recommended.

It is a modular component library divided into multiple packages (which can be installed separately) :

  1. core– 30+ components, over 300 ICONS.
  2. datetime– 6 components about dates and times.
  3. icons-300 + icon, support SVG and Fonts format.
  4. select– Drop down to select six related components.
  5. table– Highly interactive table components (I don’t think so).
  6. timezone– Handles time zone related components.
  7. popover– Powerful popup component, based onPopper.js
  8. tooltip– bypopoverTo provide.
  9. contextMenu2– bypopoverTo provide.
# installation
$ yarn add @blueprintjs/core 
# use datetime
$ yarn add @blueprintjs/datetime
Copy the code

Blueprint supports Chrome, Firefox, Safari, IE 11, and Microsoft Edge.

Blueprint strictly adheres to Semver in its public API:

  • fromblueprintroot/mainModule export JS API;
  • The HTML structure of the component;
  • Render component CSS styles;

An alternative to

  • Material UI – Google’s Material Design style, customization is relatively difficult.

  • Semantic UI – Very readable and understandable code, close to the bootstrap style.

  • React Bootstrap – Bootstrap component built with React.

5. Form processing

Ninety percent of Web applications are in this situation – processing form input is a huge pain. But we have some good ideas.

recommended

React Hook Form is the latest and greatest library (in my opinion) for handling forms, and it’s very efficient and flexible.

  • react-hook-form

It has good support for external design libraries such as Material – UI and Ant – Design.

# installation
$ npm i react-hook-form --save
# or
$ yarn add react-hook-form
Copy the code

Example:

import React from 'react' import { useForm } from 'react-hook-form' export default function HookForm() { const { register, handleSubmit, watch, formState: { errors }, } = useForm() const onSubmit = (data) => console.log(data) Return (// handleSubmit validates user input before calling onSubmit <form onSubmit={handleSubmit(onSubmit)}> {/* Register input to hook */} <input defaultValue="test" {... Register ('username')} /> {/* Register is used to configure authentication rules */} <input {... register('password', { required: True})} /> {/* The validation rule is invalid, } {errors.exampleRequired && <span>This field is required</span>} <input type="submit" /> </form>)}Copy the code

An alternative to

There are some great options in this area.

  • Formik – FormIK provides a time-tested solution for input validation, formatting, masking, arrays, and error handling.

  • Redux-form – Not recommended, it can really hurt performance.

6. The HTTP calls

In the modern world, almost all web sites rely on some external data source, so making HTTP calls is straightforward.

recommended

Axios is the recommended way to make HTTP calls.

  • Axios – an HTTP client based on promises for browsers and NodeJS.

Axios has the following characteristics:

  1. Create an XMLHttpRequest from the browser;

  2. Make HTTP requests from Node.js;

  3. Support the Promise API;

  4. Intercepting requests and responses;

  5. Transform request and response data;

  6. Cancel the request;

  7. Automatically convert JSON data;

  8. The client supports CSRF/XSRF prevention.

# installation
$ npm i axios --save
# or 
$ yarn add axios
Copy the code
// axios
axios.get(url)
  .then((response) = > console.log(response))
  .catch((error) = > console.log(error))
Copy the code

An alternative to

  • Fetch – Browser native API, distinct from XHR.

Fetch is a good solution for small projects where only a few simple API calls are required.

// fetch
fetch(url)
  .then((response) = > response.json())
  .then((data) = > console.log(data))
  .catch((error) = > console.log(error))
Copy the code

Style of 7.

You will need styles, of course, and there are several ways to style your application.

recommended

Many people may disagree with me, but I think the Styled Components are the best choice for styling in the React application.

  • styled-components

Styled Components is an implementation of CSS in JS, and other implementation methods include Radium, React-JSS, etc.

It helps to create clean components with a clear separation of concerns, and in addition, it can be easily managed and configured through props.

# installation
$ npm i styled-components --save
# or
$ yarn add styled-components 
Copy the code

Example:

import React from "react";
import styled from "styled-components";

const Container = styled.div`
	padding: 12px;
	background: red;
	&:hover {
		background: blue;
}
`
const Homepage = () => {
  return (
  	<Container>
    	<h1>Welcome to React<h1>
    </Container>
  )
}
Copy the code

An alternative to

But, as I said, there are other great options!

  • Cascading Style Sheets (CSS) – W3C standard, should be fine for smaller projects.
  • Sas-css preprocessing, which provides great functionality for managing CSS, is suitable for medium-sized and even larger projects.
  • styled-jsx- andstyled-compomnentsA library with very similar functions.
  • Radium – CSS in JS implementation.
  • An implementation of react-JSS-CSS in JS.

8. The document

Good documentation can save 100 + hours in the future, so be proactive in adopting document libraries early in the project.

recommended

The recommended method for creating documents is react-styleguidist.

  • react-styleguidist

React Styleguidist is based on React – DocGen, which helps React projects quickly build project documentation libraries.

It works by using React-DocGen to parse source files (untranslated). React – DocGen looks for the react component exported and generates documentation according to the PropTypes or Flow annotations.

React Styleguidist uses Markdown documentation: Each block of JavaScript code is rendered as an interactive demo with react-simply-code-Editor (all of these blocks are extracted using Remark).

Webpack Loaders generates JavaScript modules containing all user components, documentation, and examples and passes them to the React application, which renders the style guide.

# Install (node >= 14.0.0)
npm install react-styleguidist --save-dev
yarn add react-styleguidist --dev
Copy the code

To use React Styleguidist, you need to create the styleguide.config.js file in the project root directory. The basic configuration is as follows:

// styleguide.config.js
module.exports = {
  title: 'React Style Guide Example'.defaultExample: true.webpackConfig: {
    module: {
      rules: [{test: /\.jsx? $/,
          exclude: /node_modules/,
          loader: 'babel-loader',},... ] ,,}}}Copy the code

If you are using the React project built on Vite2, you will need to manually install the Babel dependencies:

# babel 7
$ yarn add babel-loader @babel/core @babel/preset-env babel/preset-react --dev
Copy the code

Then add the Babel configuration. Babelrl:

// .babelrc
{
	"presets": [
		"@babel/preset-env"."@babel/preset-react"]}Copy the code

By default, React Styleguidist searches for the location of components using glob mode: SRC /components/**/*.{js, JSX,ts, TSX}, which means that only components in this path will generate documents.

The React Styleguidist documentation interface is shown above.

An alternative to

There are other options.

  • Js-docs – A general purpose document tool for JavaScript.
  • React – Docz – Very easy to use documentation guide, worth a try.

9. Multilingual support

If you’re building products on a global scale, you might want to add multilingual support to your React application.

recommended

  • react-i18next

Support for internationalization of React applications using i18Next and I18N ecosystems.

  • i18next

An alternative to

There are other good options.

  • react-intl

It also supports other frameworks, such as VueJS and Angular.

Animated 10.

Animations bring your application to life. There are some good options for using animations in React.

recommended

Pure CSS is the best way to animate React applications. It’s simple, fast, and has guaranteed performance.

  • CSS Animations – W3C standard CSS Animations.
const [name, setName] = useState(' ')...function App() {
  return (
    <div>
    	<div className={['example', name].join(' ')} ></div>
      <button onClick={()= >Elegantly-named setName (' example - animation ')} > click</button>
    </div>)}Copy the code
.example {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-duration: 4s;
}

.example-animation {
  animation-name: example;
}

@keyframes example {
  0%   {background-color: red; }25%  {background-color: yellow; }50%  {background-color: blue; }100% {background-color: green;}
}
Copy the code

An alternative to

If you want something off the shelf. So here are some suggestions for you.

  • React – Motion – a cross-platform library written by Cheng Lou.

The library incorporates some physics and provides some more powerful apis for TransitionGroup of React (prior to V2).

  • React-spring – One of the official recommended libraries.

Animation library based on spring physics can basically meet most uI-related animation needs.

  • React-transition-group – One of the official recommended libraries.

A set of components for managing component state (including load and unload) over time, designed specifically for animation.

  • Framer-motion – Production ready animation, gesture library.

11. Long list rendering

Rendering a long list can seriously affect the performance of your application, in which case using libraries can be a good idea.

recommended

If you have some kind of app that scrolls infinitely, then you should consider React Window.

  • React-window-antd virtual list solution

React-window is a more lightweight Mode of React-Virtualized, same writer (React core team).

# installation
$ npm install react-window --save
# or
$ yarn add react-window
Copy the code

An alternative to

  • react-virtualized

  • React – Paginate – If you don’t need to scroll the list indefinitely, then you can paginate the data.

Code quality tools

Linters can see statically any errors in code, and it’s a good idea to use some kind of linter.

recommended

The preferred solution is Eslint.

  • eslint
Install (node.js (^10.12.0, or >=12.0.0))
$ npm install eslint --save-dev
# or
$ yarn add eslint --dev
Copy the code

Using Eslint requires configuration, and Eslint –init automatically generates the configuration file eslintrc.js in the project root directory.

$ npx eslint --init
# or 
$ yarn run eslint --init
Copy the code

Eslint configuration files support multiple formats, in the following order of priority:

  1. .eslintrc.js
  2. .eslintrc.cjs
  3. .eslintrc.yaml
  4. .eslintrc.yml
  5. .eslintrc.json
  6. package.json

An alternative to

  • Jshint – Older library.
  • Tslint-typescript linter is not currently recommended.

13. The formatting

Having a consistent visual style is important for any application, and a code formatter can do the job for you!

recommended

  • prettier

This is the best solution for you, you don’t need anything else!

# installation prettier
$ npm install prettier --save-dev --save-exact 
# or 
$ yarn add prettier --dev --exact
Copy the code

Prettier requires a configuration file when Prettier is used, Prettier follows cosmiconfig, so you can configure it (in order of precedence).

  • inpackage.json, provideprettierField.
  • It could be a.prettierrcFile, written in JSON or YAML format.
  • It can also be.prettierrc.json..prettierrc.yml..prettierrc.yamlOr,.prettierrc.json5File.
  • You can also use.prettierrc.js,.prettierrc.cjs,prettier.config.jsprettier.config.cjsthroughmodule.exportsThe export.
  • a.prettierrc.tomlFile.

For example, by using the.prettierrc file:

{
  "trailingComma": "es5"."tabWidth": 4."semi": false."singleQuote": true
}
Copy the code

All files can then be formatted using command line commands.

$ npx prettier --write .
# or 
$ yarn prettier --write .
Copy the code

Prettier can also be integrated with an editor, as detailed.

Analysis of 14.

Data analytics is the future, and most businesses today are data-driven, so it’s important to have a good analytics tool for your applications!

recommended

The most popular and powerful tool is React Ga.

  • react-ga

I don’t think you need anything else.

# installation
$ npm install react-ga --save
Copy the code

After the reactga. initialize parameter (the ID generated by Google Analytics) is initialized, the React project automatically introduces the Google Analytics script into the header.

15. The test

I don’t need to reiterate the importance of testing for any application. So read on!

recommended

The React Testing Library is an alternative to Airbnb’s Enzyme Testing Library.

The React Testing Library is different from Jest. It is one of the libraries (along with enzymes, etc.) that tests React components.

  • react-testing-library

It is very easy to use and is designed to follow real-world usage.

The React Testing Library does not directly test the implementation details of components, but rather tests them from the standpoint of a React application. More in line with our original aspirations for unit testing and best practices.

It makes your test library maintainable in the long run, makes refactoring a breeze, and component refactoring (which changes implementation but not functionality) doesn’t break your tests.

# installation
$ npm install --save-dev @testing-library/react
# or
yarn add @testing-library/react --dev
Copy the code

Example:

// hidden-message.js
import * as React from 'react'

// NOTE: React Testing Library works well with React Hooks and classes.
// Your tests will be the same regardless of how you write your components.
function HiddenMessage({children}) {
  const [showMessage, setShowMessage] = React.useState(false)
  return (
    <div>
      <label htmlFor="toggle">Show Message</label>
      <input
        id="toggle"
        type="checkbox"
        onChange={e= > setShowMessage(e.target.checked)}
        checked={showMessage}
      />
      {showMessage ? children : null}
    </div>)}export default HiddenMessage
Copy the code
// __tests__/hidden-message.js
import '@testing-library/jest-dom' // Jest-dom makes it easier to add assertions for tests. It is recommended, but not required
import * as React from 'react'
import {render, fireEvent, screen} from '@testing-library/react'
import HiddenMessage from '.. /hidden-message'

test('shows the children when the checkbox is checked'.() = > {
  const testMessage = 'Test Message'
  render(<HiddenMessage>{testMessage}</HiddenMessage>)
  // Query * returns the element, or null if it cannot be found
  // Get * returns the element, or throws an error if it cannot be found
         
  expect(screen.queryByText(testMessage)).toBeNull()
  // Queries can accept regular expressions, making selectors more flexible to content adjustments and changes
  fireEvent.click(screen.getByLabelText(/show/i))

  //.tobeintheDocument () is a jest-dom assertion
  You can also use.tobedefined ()
  expect(screen.getByText(testMessage)).toBeInTheDocument()
})
Copy the code
  • Jest – the most popular JS testing framework.

Jest is Facebook’s oldest testing framework and the default test library for Create-React-app.

The functions of Jest and React Testing Library are different. The React Testing Library works with React and Jest works with test cases.

Jest gives us the ability to run tests, but there’s also an array of apis like Test Suites, Test Cases, assertions, and not only that, but spies, Mocks, Stubs, and more.

If the React program is created using CRA, you only need to install the React-test-renderer to render the snapshot. Snapshot testing is part of Jest. You can use the test renderer to quickly render the serializable HTML output of the virtual DOM, rather than rendering the UI of the entire application.

$ yarn add react-test-renderer --dev
Copy the code

An alternative to

  • cypress

Cypress is often compared to Selenium; However, Cypress is fundamentally and architecturally different. Cypress is not subject to the same restrictions as Selenium.

It can do end-to-end testing, unit testing, integration testing, you can test anything that runs in the browser.

# installation
$ npm install cypress --save-dev
# or
$ yarn add cypress --dev
Copy the code

16. Build shareable components

If you’re on a large team, the ease with which components can be shared can be a big problem.

recommended

  • storybook

If you’re looking for the most complete solution, Storybook is your best bet.

Storybook is a rapid development environment for UI components. It allows you to browse component libraries, see the different states of each component, and develop and test components interactively. StoryBook helps you develop components independently of your application, which also helps make them reusable and testable.

# installation storybook
$ npx sb init
Copy the code

Storybook needs to be installed in projects that have already been framed; it is not suitable for empty projects. There are many ways to bootstrap an application within a given framework, including:

  • 📦 Create an Angular Workspace

  • 📦 Create the React App

  • 📦 Vue CLI

  • 📦 Ember CLI

  • Other build tools (e.g. Vite, etc.).

Finally, I think you now have a good idea of when to choose which library, so if you have any different ideas, let me know in the comments.

This paper is inspired by 45-NPM-packs-to-solve-16-react-problems.