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

Caveats

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.