r/reactjs • • Oct 26 '22
Needs Help Custom hook arguments best practices?
React newbie here. I find myself writing components that may have 2 or 3 hooks being dependent on one another. For example, hook 1 retrieves a query string parameter, which is then used in hook 2 to fetch data from an API, and the resulting data will then be used as parameter to hook 3.
Since hooks have to run non-conditionally, I can't place hook 2 and 3 within conditional statements to check if their arguments exist first. That means these hooks will HAVE to be called even when their arguments may be undefined.
In other words, is the best practice around custom hooks that they should *always* expect undefined arguments, or alternatively that there should be a flag argument to stop the hook running (a la react-query "enabled" flag?
I find it weird that there isn't clear guidance on that, maybe I missed something about React.
View all comments
Show parent comment
1
u/iams3b Oct 26 '22
Ah yeah, I'm not too familiar with next but in this case I would explicitly check for undefined in the 2nd hook. The reason there is no guidance here is because this is a specific use case, but in general I typically design things to always have a value