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:
import React from "react";
import { useTitle } from "react-use";
export default function App() {
useTitle("Hello world!");
return <div className="App" />;
}
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:
import React from "react";
import { usePermission } from "react-use";
export default function App() {
const state = usePermission({ name: "geolocation" });
return <pre>{JSON.stringify(state, null, 2)}</pre>;
}
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:
import React from "react";
import { useEffectOnce } from "react-use";
export default function App() {
useEffectOnce(() => {
console.log("running");
return () => {
console.log("cleaning up");
};
});
return <div />;
}
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:
import React from "react";
import { useList, useEvent } from "react-use";
export default function App() {
const [list, { push, clear }] = useList();
const onKeyDown = React.useCallback(({ key }) => {
if (key === "x") {
clear();
}
push(key);
}, []);
useEvent("keydown", onKeyDown);
return (
<div>
<pre>{JSON.stringify(list, null, 2)}</pre>
</div>
);
}
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:
import React from "react";
import { useLifecycles } from "react-use";
export default function App() {
useLifecycles(() => console.log("mounted"), () => console.log("unmounted"));
return <div />;
}
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.