Build and publish your own React Hook to npm

Build and publish your own React Hook to npm

Whenever you build React applications at scale you find yourself repeating certain blocks of code that you can reuse. The first thought that comes to mind is creating a react hook that you can call from multiple components in order to keep your code maintainable. But, what happens if you need to use the same hook for another project? Some developers will just copy the entire code and use it in the new project. Then after a while, you might catch a bug or you may want to improve the hook to add additional functionalities. The problem is that you need to update the same file in all the projects where you have used that hook. In order to avoid this tiresome and dangerous approach , we can create our own hook and deploy it to npm.  This will allow us e to use version control whenever we do changes and publish it to npm.  Our apps can simply be updated to use the latest version and we are good to go.

For this example we will create our own pagination hook that will take an array and slice it into chunks, and we can use it to paginate our data whenever we need to.

In order to create our hook package we will use these awesome library called create-react-hook:

npx create-react-hook use-pagination

You will have to answer all the questions that are related to your package and you are ready to get it rolling.

The src folder is for our hook, and in the example folder you can test the hook in a React application.

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;

Now that we have the code for the pagination let's explain it step by step.

This hook accepts 2 parameters, one is the data, in this case an array that we want to paginate, and the other one is itemsPerPage. For this hook to work we need to give it 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));
};

These three functions as described here are responsible for: going to the next page, previous page and jumping to a specific page with a number.

After all of this we return these functions along with the currentData, currentPage and maxPage.

In order to test our hook we need to go to the example/src/App.js and update the hook with our own as so.

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 we have to go to the root of the project and run npm run start, then on another cmd tab we need to go to cd example && npm run start. This will spin the React application so we can test our react hook.

For this scenario I am using an example dataset of movies to test if the pagination is working, and I am using two buttons to circle through the paginated data using the two functions that we implemented in the hook.

If you are happy with the results, you need to run npm login so we can login to npm, and then run npm publish. After a few minutes the package should be on npm in your account. For more info regarding the create-react-hook library, please visit their documentation.