Table of contents
I have written several articles in an attempt to cover the commonest react hooks that I use and encounter.
In the process I have relearnt the workings of useContext, relearned useRef and explored the depths of useState. There's more here: Nate's Blog Home if you care to read more.
After several readings and code implementations down the line, I realised that I had not even explored what a hook is, outside of Reactland.
So let's take a look at a hook first, as it is ubiquitous a word in the software development world.
Let’s consider this scenario:
Say you bought a tesla, and the car’s system comes with an operating system, already compiled and baked into the car, but what if you wanted your car to shout “MO POWA BABEH!” anytime your battery runs out?
That isn’t a functionality teslaOS will provide for you out of the box, that’s a custom functionality, alien to the OS, If Tesla wants you to be able to add such simple tasks, they can give you an interface (API), so you can plug in your custom code that will execute in the event preferred, for example, “low battery”.
Assuming your custom code is as below:
func scream () {
shout("MO POWA BABEH!")
}
and you will pass scream (your code) to the Tesla OS and hook it into the “fuelFinished” event.
TeslaOS.hook("fuel-finished", scream)
and so even though you don’t know the internals of the tesla OS, you are assured that whenever your fuel runs out, your tesla is gonna scream a ridiculous DONUT media jargon.
Now to a relatable example:
Let’s say you are creating a social media app that displays a certain status component to indicate whether or not a user is online. (This example is from the React docs on custom hooks)
In this example, a functionality is isolated into a custom so that it’s reusable and cleaner, both genuinely good reasons to use custom hooks.
import React, { useState, useEffect } from 'react';
function FriendListItem(props) {
// 👇 to be extracted to custom hook
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
// 👆 to be extracted to custom hook
return (
<li style={{ color: isOnline ? 'green' : 'black' }}>
{props.friend.name}
</li>
);
}
As shown below the functionality in the above component is extracted into the custom useFriendStatus hook below.
import { useState, useEffect } from 'react';
// "Its name should always start with use so that you can
// tell at a glance that the rules of Hooks apply to it." - the docs
function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
};
});
return isOnline;
}
The custom hook can be used in a component that needs to display a user’s online status as shown below:
function FriendListItem(props) {
const isOnline = useFriendStatus(props.friend.id);
return (
<li style={{ color: isOnline ? 'green' : 'black' }}>
{props.friend.name}
</li>);
}
// You can notice that, as compared to the first implementation of the same logic, this is much cleaner and DRY.
Due to the usefulness and utility of react hooks, there are several already made hooks that you can implement in your codebase for speed and simplicity.
React has some inbuilt hooks too like the useReducer hook.
Find more useful examples here: useHooks.com
References:
React hooks: The Official Docs](https://reactjs.org/docs/hooks-custom.html
Hook Scenario: Originally posted in DevCongress Slack Community](https://devcongress-community.slack.com/archives/C031NH6AVFV/p1655893823250159?thread_ts=1655891227.669889&cid=C031NH6AVFV