DEV Community

Discussion on: Writing Your Own React Hooks - a TDD Example

namick profile image
nathan amick Author • Edited

Interesting question. I was just thinking of doing a post on this, but the short of it is that each have their use cases.

A hook that has very general use cases benefits from exporting return values as an array. A great example of this is actually the built-in useState hook. By exporting an array with two values, it makes it easy to customize the names of the state variables and their setters and to use them repeatedly:

const [color, setColor] = useState()
const [count, setCount] = useState()

Hooks that are more custom or specific to a component or set of components and return a larger number of values may benefit by returning an object. Object destructuring doesn't rely on ordering and it is easier to ignore values that are not needed. An example might be a hook that 3 or 4 state values along with handler functions:

const { color, count, isValid, handleChangeColor, handleChangeCount } = useItemOptions()

There are tradeoffs and some overlap, so it comes down to figuring out what the best API is for each specific hook.

I'll try to come up with some better examples in a future post.

seanmclem profile image

Thanks, great answer! I don't think anyone would mind if you still made a blogpost about it. But you answered my question