Top React Hooks — Permissions, Titles, Lifecycle

Image for post
Image for post
Photo by Kaleidico 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.

useTitle

The useTitle hook lets us set the title of a page.

We can use it by writing:

We pass the string to the hook to set the title.

usePermission

We can use the usePermission hook to query the permission status of browser APIs.

For instance, we can write:

to get the location given the value of the name property of the object we pass into the hook.

useEffectOnce

The useEffectOnce let us run a side effect only once.

For instance, we can write:

We have the useEffectOnce hook with a callback that runs when the component mounts.

The function that’s returned is run when the component unmounts.

This is handy for running any cleanup code.

useEvent

The useEvent hook lets us listen for events in our code.

For instance,e we can write:

We listen to the keydown event by passing in a callback.

The callback takes an event object with the key property for the key.

The useList hook returns the list which has the list.

push lets us push to list .

clear lets us clear the list .

If ‘x’ is pressed then the list is cleared.

Otherwise, we push the key that’s pressed to the list .

And we pass that into the 2nd argument of useEvent to run it on key down.

useLifecycles

The useLifecycles hook lets us pass in callback to run when the component mounts and unmounts.

We can use it by writing:

The useLifecycke hook takes 2 arguments.

The first is the callback that runs when the component mounts.

The 2nd is the callback that runs when the component unmounts.

Conclusion

The react-use library lets us create lifecycle methods, change the title of the page, and query for browser permissions.

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