A custom Hook is a JavaScript function whose name starts with use
and that may call other Hooks.
Custom Hooks can be used when we want to reuse some stateful logic between components.
- Your should name your custom Hooks starting with
use
(need it in order to check if you follow the the rules of Hooks) - Two components using the same custom Hook do not share any state (they only share stateful logic)
Here is a simple example of a custom Hook for a rocket's takeoff status:
import React, { useState, useEffect } from 'react';
function useReadyForTakeoffStatus(rocketID) {
const [isReadyForTakeoff, setIsReadyForTakeoff] = useState(null);
useEffect(() => {
const handleStatusChange = (status) => {
setIsReadyForTakeoff(status);
}
handleStatusChange(SpaceXAPI.getStatus(rocketID));
});
return isReadyForTakeoff;
}
We can use the custom Hook, useReadyForTakeoffStatus
like this:
const ReadyForTakeoffComponent = ({ rocketID }) => {
const isReadyForTakeoff = useReadyForTakeoffStatus(rocketID);
return (
<div>
The rocket is {!isReadyForTakeoff && 'not yet'} ready for takeoff.
</div>
);
}