Top React Hooks — State and API

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:

npm install nice-hooks

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

For instance, we can write:

import React from "react";
import { useLifeCycle } from "nice-hooks";
export default function App() {
useLifeCycle({
didMount() {
console.log("mounted");
},
willUnmount() {
console.log("willUnmount");
},
didUpdate() {
console.log("didUpdate");
},
didMountAndWillUnmount: [
{
didMount() {
console.log("didMount");
},
willUnmount() {
console.log("willUnmount");
}
},
{
didMount() {
console.log("didMount");
},
willUnmount() {
console.log("willUnmount");
}
}
]
});
return <div />;
}

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:

import React from "react";
import { useInstanceVar, useSingleState } from "nice-hooks";
export default function App() {
const [getIntervalVal, setIntervalVal] = useInstanceVar(null);
const [state, setState] = useSingleState({ count: 0 });
function start() {
const interval = setInterval(
() => setState({ count: state.count + 1 }),
1000
);
setIntervalVal(interval);
}
function stop() {
const interval = getIntervalVal();
interval && clearInterval(interval);
}
return (
<div>
<p>{state.count}</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
);
}

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:

yarn add promise-hook

or:

npm i promise-hook --save

Then we can use it by writing:

import React from "react";
import { usePromise } from "promise-hook";
const fetchName = () =>
fetch(`https://api.agify.io/?name=michael`).then(res => res.json());
export default function App() {
const { isLoading, data } = usePromise(fetchName, { resolve: true });
return isLoading ? <div>Loading...</div> : <div>{JSON.stringify(data)}</div>;
}

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:

import React from "react";
import { usePromise } from "promise-hook";
const fetchName = name =>
fetch(`https://api.agify.io/?name=${name}`).then(res => res.json());
const Name = ({ name }) => {
const { isLoading, data } = usePromise(() => fetchName(name), {
resolve: true,
resolveCondition: [name]
});
return isLoading ? <div>Loading...</div> : <div>{JSON.stringify(data)}</div>;
};
export default function App() {
return <Name name="james" />;
}

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.

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.

Web developer. Subscribe to my email list now at https://thewebdev.info/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