Build a React Hook and Publish to NPM Packages

react-hook-typescript

This is a small tutorial for how to build a custom React custom hook.

React hooks are more popular now with functional components and provides a way to use React state and lifecycles. One can convert component business logic to a custom hook. It will make your code cleaner and manageable. Let’s see how.

There is two core React hooks:

  • useState
  • useEffect

useState Hook

React’s useState home is used to create a state in the functional component. React will preserve this state between re-renders. useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to this.setState in a class, except it doesn’t merge the old and new state.

useEffect

The effect hook adds the ability to handle side effects and mimic the lifecycle of react similarly to class-based components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API. When you call useEffect, you’re telling React to run your “effect” function after flushing changes to the DOM.

Building Your Own Hook ?

We will build a custom hook to use browser storages with an option to use localStorage and sessionStorage for this tutorial.

useBrowserStorage

If a function name starts with “use” then it is called a hook. The useBrowserStorage naming convention is how linter plugin is able to find bugs in the code using Hooks.

Setup

The quickest way to start, by using a boilerplate. So that you don’t need to worry about adding dependencies and build tools. We will be using create-react-hook NPM package to boilerplate the project.

https://www.npmjs.com/package/create-react-hook

npx create-react-hook <hook-name>

After running this command answers some question and the CLI will setup the project.

Write Your Logic

Now you have come this far, let’s write our useBrowserStorage hook logic. If you have setup the project using create-react-hook CLI then there is an entry file in src/index.(jsx, tsx) which has some example code to write hook. Let’s replace it.

export const useBrowserStorage = () => {
  // logic will go here
}

We will provide one option { type } to switch between localStorage and sessionStorage . Default value for type is localStorage .

const STORAGE_TYPES = ['localStorage', 'sessionStorage'];
export const useBrowserStorage = (options = {}) => {
  const type = (STORAGE_TYPES.includes(options.type) && options.type) || 'localStorage';
}

Now let’s check if browser supports storages. It will also be checked if our hook is run on server side then it will not generate any error.

https://medium.com/media/5c07bfd2d6534165bf88cb75f8e14e0f/href

Finally combined together in one file

https://medium.com/media/0c5698d8aba868da4704504533eae2ad/href

Publish To NPM

Once we are ready with our hook, let’s publish it to NPM packages.

Login to NPM CLI. Enter your username, password and email to login.

npm login

Once logged-in successfully, let’s run this command to publish

npm publish

That’s it!!!

Tip: if you want to publish you package again with new changes or bug fixes. Then you have to update your package version. You can manually update the package version into package.json file or you can run this command:

npm version patch -m "message"

Read more for npm version command

Here is the full source code of useBrowserStorage

Hope you like this tutorial. Thank you for reading!!!


Build a React Hook and Publish to NPM Packages was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.

react-hook-typescript

This is a small tutorial for how to build a custom React custom hook.

React hooks are more popular now with functional components and provides a way to use React state and lifecycles. One can convert component business logic to a custom hook. It will make your code cleaner and manageable. Let’s see how.

There is two core React hooks:

  • useState
  • useEffect

useState Hook

React’s useState home is used to create a state in the functional component. React will preserve this state between re-renders. useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to this.setState in a class, except it doesn’t merge the old and new state.

useEffect

The effect hook adds the ability to handle side effects and mimic the lifecycle of react similarly to class-based components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API. When you call useEffect, you’re telling React to run your “effect” function after flushing changes to the DOM.

Building Your Own Hook ?

We will build a custom hook to use browser storages with an option to use localStorage and sessionStorage for this tutorial.

useBrowserStorage

If a function name starts with “use” then it is called a hook. The useBrowserStorage naming convention is how linter plugin is able to find bugs in the code using Hooks.

Setup

The quickest way to start, by using a boilerplate. So that you don’t need to worry about adding dependencies and build tools. We will be using create-react-hook NPM package to boilerplate the project.

https://www.npmjs.com/package/create-react-hook

npx create-react-hook <hook-name>

After running this command answers some question and the CLI will setup the project.

Write Your Logic

Now you have come this far, let’s write our useBrowserStorage hook logic. If you have setup the project using create-react-hook CLI then there is an entry file in src/index.(jsx, tsx) which has some example code to write hook. Let’s replace it.

export const useBrowserStorage = () => {
  // logic will go here
}

We will provide one option { type } to switch between localStorage and sessionStorage . Default value for type is localStorage .

const STORAGE_TYPES = ['localStorage', 'sessionStorage'];
export const useBrowserStorage = (options = {}) => {
  const type = (STORAGE_TYPES.includes(options.type) && options.type) || 'localStorage';
}

Now let’s check if browser supports storages. It will also be checked if our hook is run on server side then it will not generate any error.

Finally combined together in one file

Publish To NPM

Once we are ready with our hook, let’s publish it to NPM packages.

Login to NPM CLI. Enter your username, password and email to login.

npm login

Once logged-in successfully, let’s run this command to publish

npm publish

That’s it!!!

Tip: if you want to publish you package again with new changes or bug fixes. Then you have to update your package version. You can manually update the package version into package.json file or you can run this command:

npm version patch -m "message"

Read more for npm version command

Here is the full source code of useBrowserStorage

Hope you like this tutorial. Thank you for reading!!!


Build a React Hook and Publish to NPM Packages was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


Print Share Comment Cite Upload Translate
APA
Ravi Dhiman | Sciencx (2024-03-28T21:37:11+00:00) » Build a React Hook and Publish to NPM Packages. Retrieved from https://www.scien.cx/2021/02/25/build-a-react-hook-and-publish-to-npm-packages/.
MLA
" » Build a React Hook and Publish to NPM Packages." Ravi Dhiman | Sciencx - Thursday February 25, 2021, https://www.scien.cx/2021/02/25/build-a-react-hook-and-publish-to-npm-packages/
HARVARD
Ravi Dhiman | Sciencx Thursday February 25, 2021 » Build a React Hook and Publish to NPM Packages., viewed 2024-03-28T21:37:11+00:00,<https://www.scien.cx/2021/02/25/build-a-react-hook-and-publish-to-npm-packages/>
VANCOUVER
Ravi Dhiman | Sciencx - » Build a React Hook and Publish to NPM Packages. [Internet]. [Accessed 2024-03-28T21:37:11+00:00]. Available from: https://www.scien.cx/2021/02/25/build-a-react-hook-and-publish-to-npm-packages/
CHICAGO
" » Build a React Hook and Publish to NPM Packages." Ravi Dhiman | Sciencx - Accessed 2024-03-28T21:37:11+00:00. https://www.scien.cx/2021/02/25/build-a-react-hook-and-publish-to-npm-packages/
IEEE
" » Build a React Hook and Publish to NPM Packages." Ravi Dhiman | Sciencx [Online]. Available: https://www.scien.cx/2021/02/25/build-a-react-hook-and-publish-to-npm-packages/. [Accessed: 2024-03-28T21:37:11+00:00]
rf:citation
» Build a React Hook and Publish to NPM Packages | Ravi Dhiman | Sciencx | https://www.scien.cx/2021/02/25/build-a-react-hook-and-publish-to-npm-packages/ | 2024-03-28T21:37:11+00:00
https://github.com/addpipe/simple-recorderjs-demo