BRIEFS logo BRIEFS

Avoid Hasty Abstractions: Hooks edition

06/07/2021 , 2m, 59s

Hello friends, so I wanted to talk today about whether or not you should make a custom hook for everything. So a few days ago, maybe last week there was this thing going around where people were recommending that you never ever use the react built-in hooks inside of a component, you always extract it to a custom hook.

This is terrible advice. Don't do that at all. So the way that I think about hooks in React is the they're basically functions that have the,Only special distinction of being functions that actually call other hooks. That's the only thing special about them. So everything else about this function is the same as regular functions.

And you don't make a function for every line of code that you write right? Like that would be ridiculous. The reason that we make functions is to encapsulate certain logic. And most of the time it's useful mostly for reuse. Sometimes it could be nice to take a bunch of chunks of code.

And logically put it together so that it can be separate from the rest of our our code, but you've got to keep in mind that every single time you abstract something into another function you're adding complexity. And now you have to pass parameters and and maybe you didn't pass enough and so now you need to update those in the except the additional parameters and and and then if you're doing TypeScript, you have to make sure that you're typing for those parameters is correct and and potentially worry about the return value and then oh what if now weDecide that there's some logic in this function that says never mind let's return early or let's throw an error or something like that.

Now, you have to start worrying about the consumer and say, oh well, they wanted to return early from here. So, I'll return early. It just gets to be more complex. There are more things to think about. So you can't avoid adding complexity when you start abstracting things into functions.

It's just the way that it is it always adds complexity. Now whether or not it makes your code simple or more simple.Is a different matter or sorry let me say that differently whether or not it makes it easier for you as the the writer of the coder and the maintainer of the code to understand what's going on.

That's a different matter. But the fact is that it will always increase complexity to extract things into separate functions and that is no different with hooks. This is especially relevant if you wanted to abstract just the use effect part, but you want to pass in some sort of function that's going to get called within that effect.

That means that you'll either need to.Call back that your passing in or you have to use the latest ref pattern to always use the latest function. So anyway, hope that helps.