Single-use hooks
A single-use hook is a custom hook that is designed to only ever have one instance. They can be useful for wrapping up logic related to a particular component or process.
While custom hooks are generally encouraged for splitting out shared logic that can be used in many places, single-use hooks can be used to wrap up related logic for a specific component purely for structural and DX reasons.
Benefits
- Simplifies a component by extracting large chunks of logic and replacing them with a simple hook call. Component functions are now focused on the presentation layer.
- Allows us to change any internals or implementation details of the hook without updating the consumer (unless we change what it exposes).
- Encourages thinking about the logic in isolation. “What is this hook’s job?”
Caveats
- Slightly increases the cognitive overhead of getting a big-picture view of a component, as we now have another abstraction to dig into.
- We need to ensure that the hook only has one instance. Multiple instances will likely cause unexpected behaviour - e.g. if the hook contains any stateful logic it may be duplicated and have separate instances.
Use case: Wrangling a bloated component
Imagine a component with a complex render function.
Maintaining and extending these kinds of components can be cumbersome, and it’s not always immediately obvious where to put new code as they grow. They also tend to have logic with dependencies that are spread out across the file. While this can sometimes be an indicator that the component is doing too many jobs, you might be working with a component that has a valid need to responsible for a wide set of logic.
We can create a single-use hook, or multiple single-use hooks, purely for the purpose of organising the logic inside the component. This will make the component function more readable - anyone that needs to work with this component in future will be able to grasp what it's doing at a glance. They can then dive into specific logic as needed by looking at the related single-use hook in isolation.