Member-only story
Building Our Own React Hooks
React is a library for creating front end views. It has a big ecosystem of libraries that work with it. Also, we can use it to enhance existing apps.
In this article, we’ll look at how to build our own React hooks.
Building Our Own Hooks
Building our own hooks lets us extract component logic into reusable functions.
To build one, we write a function that runs code to manipulate the state and then returns the state.
For example, we can write a hook as follows:
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";const useDelayedMessage = (msg, delay) => {
const [message, setMessage] = useState(""); useEffect(() => {
setTimeout(() => {
setMessage(msg);
}, delay);
}); return message;
};function App() {
const delayedMessage = useDelayedMessage("foo", 1500);
return <div>{delayedMessage}</div>;
}
In the code above, we defined our own useDelayedMessage
hook that uses the useState
function to set a string state called message
.
Then in the function, we call the useEffect
function with a callback that has the setTimeout
method, which takes the msg
parameter and call setMessage
with it, and set the delay to delay
.
In the end, we return the message
state, so we can use it in App
.
In App
, we set the returned message
from useDelayedMessage
to delayedMessage
. We called useDelayedMessage
with 'foo'
for the msg
parameter and 1500 for the delay
.
Then we display delayedMessage
by returning it in a div.
Hooks should always start with use
so that React can check for rules of hooks violations since it’s the only way to tell them apart from ordinary functions.
2 components that use the same hook don’t share state. All states and effects are isolated when we use it.
Each call to a hook gets an isolated state. In the example above, useState
and useEffect
are called each time our hook is run.