Article image Working with Third-Party Libraries in React

46. Working with Third-Party Libraries in React

Page 90 | Listen in audio

When developing applications with React, one of the significant advantages is the ability to extend functionality through third-party libraries. This capability allows developers to leverage the work of others, saving time and effort while adding robust features to their applications. React's ecosystem is vast, and there are numerous libraries available for various purposes, from UI components to state management, data fetching, and more.

Before diving into how to work with third-party libraries in React, it's essential to understand why you might want to use them. Third-party libraries can speed up development by providing pre-built solutions to common problems, enhance performance, and improve the overall user experience. They also promote code reusability and maintainability, as well as community support and frequent updates.

Choosing the Right Library

When selecting a third-party library, consider the following factors:

  • Popularity and Community Support: A well-supported library is more likely to be maintained, receive updates, and have a community that can help with issues.
  • Documentation: Comprehensive documentation is crucial for understanding how to implement and use the library effectively.
  • Compatibility: Ensure the library is compatible with the version of React you are using.
  • Performance: Check if the library is optimized for performance, especially if it will be used in performance-critical parts of your application.
  • Size: Consider the library's size and how it will impact your application's bundle size.

Installing Third-Party Libraries

Most React libraries are available via npm or yarn, which makes installation straightforward. For example, to install a library like axios for HTTP requests, you can run:

npm install axios

or

yarn add axios

Once installed, you can import the library into your components as needed:

import axios from 'axios';

Using UI Component Libraries

UI component libraries such as Material-UI, Ant Design, or Bootstrap are popular choices for building React applications. These libraries provide a set of ready-to-use components that follow design guidelines, ensuring a consistent look and feel across your application.

For example, to use Material-UI, you first install the core package:

npm install @mui/material @emotion/react @emotion/styled

Then, you can start using components in your application:


import React from 'react';
import Button from '@mui/material/Button';

function App() {
  return (
    <div>
      <Button variant="contained" color="primary">
        Hello World
      </Button>
    </div>
  );
}

export default App;

State Management Libraries

State management is a critical aspect of React applications, and several libraries can help manage complex state logic. Redux and MobX are two of the most popular state management libraries. Redux is known for its predictable state container, while MobX is appreciated for its simplicity and reactivity.

To integrate Redux, you would install it and its React bindings:

npm install redux react-redux

Then, set up your store and provide it to your application:


import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers';
import App from './App';

const store = createStore(rootReducer);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Data Fetching Libraries

Data fetching is another critical aspect of modern web applications. Libraries like axios and react-query simplify data fetching and caching.

With axios, you can make HTTP requests as follows:


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

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

  useEffect(() => {
    axios.get('https://api.example.com/data')
      .then(response => setData(response.data))
      .catch(error => console.error(error));
  }, []);

  return (
    <ul>
      {data.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

Alternatively, react-query provides a more declarative approach:


import React from 'react';
import { useQuery } from 'react-query';
import axios from 'axios';

function fetchData() {
  return axios.get('https://api.example.com/data').then(res => res.data);
}

function DataFetchingComponent() {
  const { data, error, isLoading } = useQuery('fetchData', fetchData);

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <ul>
      {data.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

Form Handling Libraries

Handling forms in React can be cumbersome, especially when dealing with complex validation logic. Libraries like Formik and React Hook Form offer solutions to simplify form management.

Formik, for example, provides a way to manage form state and validation:


import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

function SignupForm() {
  return (
    <Formik
      initialValues={{ email: '', password: '' }}
      validationSchema={Yup.object({
        email: Yup.string().email('Invalid email address').required('Required'),
        password: Yup.string().min(6, 'Must be at least 6 characters').required('Required'),
      })}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="email" name="email" />
          <ErrorMessage name="email" component="div" />
          <Field type="password" name="password" />
          <ErrorMessage name="password" component="div" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

Testing Libraries

Testing is a crucial part of any development process, and React has a rich ecosystem for testing libraries. Jest, React Testing Library, and Enzyme are popular choices for testing React components.

Jest is a testing framework that works well with React. You can write tests like:


import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';

test('renders hello world button', () => {
  render(<App />);
  const buttonElement = screen.getByText(/hello world/i);
  expect(buttonElement).toBeInTheDocument();
});

React Testing Library is built on top of Jest and provides utilities to test React components by querying the DOM:


import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Button from './Button';

test('button click changes value', () => {
  const { getByText } = render(<Button />);
  const button = getByText(/click me/i);
  fireEvent.click(button);
  expect(button.textContent).toBe('Clicked');
});

Best Practices

When working with third-party libraries in React, consider the following best practices:

  • Read the Documentation: Always read the documentation to understand the library's API and best practices.
  • Keep Libraries Updated: Regularly update your libraries to benefit from the latest features and security patches.
  • Limit Dependencies: Use only the libraries you need to keep your application lightweight and maintainable.
  • Evaluate Alternatives: Before choosing a library, evaluate alternatives to ensure it fits your project's needs.
  • Test Thoroughly: Always test your application after integrating a new library to ensure it doesn't introduce issues.

In conclusion, third-party libraries are invaluable tools in React development. They can significantly enhance your application's functionality and streamline your development process. By choosing the right libraries and following best practices, you can build robust, efficient, and scalable React applications.

Now answer the exercise about the content:

What is one of the significant advantages of developing applications with React?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Creating Reusable Components

Next page of the Free Ebook:

91Creating Reusable Components

6 minutes

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text