Top React Hooks — State and API

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

Nice Hooks

Nice Hooks is a set of hooks that does various things.

To install it, we run:

The useLifeCycle hook lets us add lifecycle methods as we do with class components.

For instance, we can write:

We use the useLifeCycle hook to add the lifecycle hooks to our components.

The useInstanceVar hook lets us create instance variables in our component.

For example, we can write:

We use the useInstanceVar hook to create our getter and setter for our instance variable.

In the start function, we called setIntervalVal to set the instance variable value to the timer.

In the setInterval callback, we update the count state that’s returned from useSingleState .

In stop , we called getIntervalVal to get the state we set and call clearInterval on it if it’s set.

promise-hook

The promise-hook library lets us fetch data with a hook.

To install it, we install it by running:

or:

Then we can use it by writing:

We defined the fetchName function to get data from our app.

We passed that into the usePromise hook to get the data.

resolve means that we get data when the component mounts.

The isLoading state indicates whether data is loading or not.

data has the data.

We can pass arguments by writing:

We get the name prop and then pass that into the fetchName function.

resolveCondition has the value to watch for when the API is called.

Image for post
Image for post
Photo by James Hartono on Unsplash

Conclusion

Nice Hooks lets us manage state in various ways.

The promise-hook library lets us fetch data with a hook.

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