Hooks API Considerations
If you're a familiar user of react-hanger
you may notice that some of its hooks have two different APIs, one returning an array and another returning an object.
"What's the big deal?" you may ask.
A good rule when you're developing certain custom hooks APIs (mostly for those that hold and expose some state) is to keep them as close to the original React Hooks API as possible.
Let's look at a simple example using simple useState
:
import { useState, useCallback } from "react";
const OpenClosedSign = () => {
const [isOpen, setOpen] = useState(true);
const toggleOpen = useCallback(() => {
setOpen((prevOpen) => !prevOpen);
});
return (
<div>
<button onClick={toggleOpen}>Toggle</button>
{isOpen ? "Open!" : "Closed!"}
</div>
);
};
Good, all clear! There is a little boilerplate needed in order to keep reference equality of toggleOpen
between renders, so our child components are not re-rendering for no reason. This snippet can be improved by using the custom useBoolean
hook from react-hanger
(we're going to implement it in the next lesson).
import { useBoolean } from "react-hanger/array";
const OpenClosedSign = () => {
const [isOpen, isOpenActions] = useBoolean(true);
return (
<div>
<button onClick={isOpenActions.toggle}>Toggle</button>
{isOpen ? "Open!" : "Closed!"}
</div>
);
};
This is a pretty obvious API which feels like it's part of React itself, with the state on the left that is changing and our actions, setters, methods etc on the right.
This page is a preview of The newline Guide to Creating a React Hooks Library