Build and publish your own React Hook to npm

lokman musliu
Lokman Musliu

February 14, 2021 · 4 min read · 254 views

React and NPM Blogpost Image

Building React applications at scale often involves repeating certain blocks of code that could be reused. One common solution is to create a React hook that can be called from multiple components, enhancing code maintainability. But what if you need to use the same hook for another project? In this article, we'll guide you through the process of creating your own hook and deploying it to npm, which allows for version control and easy updates.

The Need for Reusable React Hooks

When developing multiple projects, some developers might simply copy the entire code and use it in the new project. However, this approach can lead to issues. For instance, if you catch a bug or want to add additional functionalities to the hook, you'll need to update the same file in all the projects where you've used that hook. This can be both tiresome and risky.

To avoid these issues, we can create our own hook and deploy it to npm. This allows us to use version control whenever we make changes and publish them to npm. Our apps can then simply be updated to use the latest version.

Creating a Pagination Hook: An Example

To illustrate this process, we'll create a pagination hook that takes an array and slices it into chunks. This hook can be used to paginate our data whenever necessary.

Setting Up the Hook Package

To create our hook package, we'll use an excellent library called create-react-hook. You can initiate it using the following command:

npx create-react-hook use-pagination

You'll need to answer all the questions related to your package, and then you're ready to start coding.

Building the Hook

The src folder is where we'll build our hook. In the example folder, you can test the hook in a React application. Here's the code for our pagination hook:

import React, { useState } from "react";

const usePagination = (data, itemsPerPage) => {
  
const [currentPage, setCurrentPage] = useState(1);
const maxPage = Math.ceil(data.length / itemsPerPage);

const currentData = () => {
  const begin = (currentPage - 1) * itemsPerPage;
  const end = begin + itemsPerPage;
  
  return data.slice(begin, end);
};

const next = () => {
  setCurrentPage((currentPage) => Math.min(currentPage + 1, maxPage));
};

const prev = () => {
  setCurrentPage((currentPage) => Math.max(currentPage - 1, 1));
};

const jump = (page) => {
  const pageNumber = Math.max(1, page);
  
  setCurrentPage((currentPage) => Math.min(pageNumber, maxPage));
};

  return { next, prev, jump, currentData, currentPage, maxPage }
}

export default usePagination;

Understanding the Pagination Hook

This hook accepts two parameters: the data (an array that we want to paginate) and itemsPerPage. We need to provide an array and specify how many items we want per page so we can slice it accordingly.

const currentData = () => {
  const begin = (currentPage - 1) * itemsPerPage;
  const end = begin + itemsPerPage;
  
  return data.slice(begin, end);
};

Using the currentData function we slice the array from the beginning to the end in order to paginate the data.

const next = () => {
  setCurrentPage((currentPage) => Math.min(currentPage + 1, maxPage));
};

const prev = () => {
  setCurrentPage((currentPage) => Math.max(currentPage - 1, 1));
};

const jump = (page) => {
  const pageNumber = Math.max(1, page);
  
  setCurrentPage((currentPage) => Math.min(pageNumber, maxPage));
};

The currentData function slices the array from the beginning to the end to paginate the data. The next, prev, and jump functions are responsible for going to the next page, the previous page, and jumping to a specific page with a number, respectively.

Finally, we return these functions along with currentData, currentPage, and maxPage.

Testing the Hook

To test our hook, we need to update the example/src/App.js file with our own hook:

import React from 'react'
import movies from './movies.json'
import usePagination from 'use-pagination'

const App = () => {
  const data = usePagination(movies, 5)

  return (
    <div>
      {data.currentData().map((item) => item.title)}

      <button onClick={data.prev}>Go Prev</button>
      <button onClick={data.next}>Go Next</button>
    </div>
  )
}
export default App

Now, go to the root of the project and run npm run start. In another command tab, navigate to the example directory (cd example) and run npm run start. This will start the React application so we can test our React hook.

In this scenario, we're using an example dataset of movies to test if the pagination is working. We're using two buttons to cycle through the paginated data using the two functions that we implemented in the hook.

Publishing the Hook to npm

If you're satisfied with the results, run npm login to log in to npm, and then run npm publish. After a few minutes, the package should be available on npm under your account. For more information regarding the create-react-hook library, visit their documentation.


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Next.js Development Agency

lokman musliu
Lokman Musliu

Founder and CEO of Lucky Media

Technologies:

React
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!