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/willdone Oct 26 '22 edited Oct 26 '22
Actually, this is not quite true. Say you want to only display some data after X + Y + Z is defined, where Y depends on X and Z depends on Y. If you have something like
if (!X || !Y || !Z) return nullthen when those hooks update the component will rerender each time, usually quite fast if you are returning null. Those hooks will have the updated state from the previous renders. Then when all three are defined you return your actual component layout. Another way of doing this I see is further extracting that entire chain of 3 hooks into a fourth hook. So if that was to return user information, you might call ituseUsersand it returns{users, refetch}or something.But to the spirit of your question, yes, the correct way is to check arguments are defined when it makes sense to do so as you will sometimes have no choice but to pass undefined or null arguments.