Top React Hooks — Async, Clipboard, and Cookie

Image for post
Image for post
Photo by SJ Baren on Unsplash

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

react-use

The react-use library is a big library with many handy hooks.

useAsyncRetry

The useAsyncRetry hook lets us run async cod with an addition rety method to let us retry or refresh the async function.

To use it, we run:

The useAsyncRetry hook takes a callback that gets data from an API.

A promise is returned and it resolves to the response body.

The state is returned by the hook.

It has the retry method to let us get the data again.

Also, it has the loading and error properties to get the loading state and error respectively.

value has the response body.

useBeforeUnload

The useBeforeUnload hook lets us show a browser alert when the user tries to reload or close the page.

To use it, we can write:

We pass in true to the first argument to enable the alert when we leave.

Then we add a string to show the content.

Most browsers don’t let us show custom text in the alert, so we can put in anything.

useCookie

useCookie is a hook that lets us return the current value of a cookie.

It also lets us update and delete the cookie.

For instance, we can use it by writing:

We call the useCookie hook with the key of the cookie to let us get, set, and delete the cookie.

value has the value.

updateCookie is a function to let us update the cookie.

deleteCookie lets us delete the cookie.

Then we used that in the useEffect callback to clear the cookie on load.

And we used updateCookie when we click the Update Cookie button.

useCopyToClipboard

The useCopyToClipboard hook lets us copy text in a string to the clipboard.

For instance, we can use it by writing:

We called the useCopyToClipboard hook to return the state and copyToClipboard variables.

state is the state of the clipboard.

copyToClipboard lets us copy the text we pass into it to the clipboard.

Conclusion

The react-use library provides us with hooks to copy data to the clipboard, create cookies, and run promises.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store