Top React Hooks — Debounce, Error, Favicon, and Local Storage

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

useDebounce

The useDebounce hook lets us denounce our callbacks by our give number of milliseconds.

For instance, we can write:

We call the useDebounce hook with a callback to set the debounced value in the callback.

The 2nd argument is the number of milliseconds to debounce.

The 3rd is an array with the values to watch for and call the callback when they change.

It’ll be debounced by the delay in the 2nd argument.

The hook returns an array with the cancel function to cancel the debouncing.

useError

The useError hook lets us throw errors in our code.

It’ll be caught with the ErrorBoundary component is we wrap our component with it.

For instance, we can write:

We create the ErrorBoundary component with methods to log the error.

The getDerivedStateFromError function runs to return the state when an error occurs.

componenrDidCatch catches the error.

The Foo component uses the useError hook, which returns the dispatchError function that takes an Error instance.

This lets us throw an error and catch it with the ErrorBoundary component.

useFavicon

The useFavicon hook lets us set the favicon of the page.

For instance, we can write:

We just call the useFavicon hook with the URL of the favicon change our app to that favicon.

useLocalStorage

To manage local storage, we can use the useLocalStorage hook.

It returns an array with the value, a function to set the value, and a function to remove the item.

The argument it takes is the key of the local storage item.

To use it, we can write:

In the code above, 'something' is the key.

value is the value of 'something' .

setValue sets the value of 'something' .

And remove removed the entry with key 'something' .

setValue takes an argument with the value to save.

Conclusion

The react-use library lets us denounce our code, throw errors, save to local storage, and change favicons.

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