Top React Hooks — Async and Window

Image for post
Image for post
Photo by Dan Gold 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 Recipes

React Recipes comes with many hooks that we can use to do various things.

The useWindowSize hook lets watch the size of the window as it changes.

For instance, we can write:

We call the useWindowSize hook to return the width and height properties.

They’re the width and height of the window.

We can also pass in the initial width and height, which are useful for server-side rendered apps.

It comes with many other useful hooks to make our lives easier.

React Request Hook

The React Request Hook library lets us make requests with ease.

To install it, we run:

or:

Then we can use it by writing:

index.js

App.js

In index.js , we create the Axios instance and pass it into the RequestProvider component.

The value prop takes the Axios instance.

Then we can use the useResource hook in App to get the data we want.

In the callback we pass in, we return the url and method .

The url is the path relative to the URL in the Axios instance.

method is the request method.

It returns an array with the result and the function to get the result.

name has the response body.

And getName is a function that takes the same parameter as the useResource callback to get the data.

Then we can call getName to get the data.

It also provides us with other ways to make requests.

React-RocketJump

React-RocketJump is another library that lets us commit async side effects in our React app.

To use it, we install it by running:

Then we can use it by writing:

We create our side effect with the rj function.

The object has the effect method which returns a promise with the data.

Then in App , we use the useRunRj hook to get the data.

We pass in NameState as the argument of the hook.

Then it returns an array with an object that has the data , pending , and error properties.

data has the response body.

pending has the pending status.

error has the error.

Conclusion

React Recipes, React Request Hook, and React-RocketJump are all useful libraries that give us various hooks to do what we want.

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