How does the top-level hook rule work within other hooks?

For example, is it OK to inline other hooks like so:
export const useToken = () => ({ value: useTokenStore(s => s.value) })
export const useToken = () => ({ value: useTokenStore(s => s.value) })
Or do you need to have it like so:
const useToken = () => {
const value = useTokenStore(s => s.value)
return { value }
}
const useToken = () => {
const value = useTokenStore(s => s.value)
return { value }
}
4 Replies
Josh
Josh13mo ago
in js world, these two statements are equivalent both of these satisfy top-level hook rule
Fredrik
Fredrik13mo ago
Fair, got the response elsewhere that whiile the current setup is valid in regards to the top-level hook rule, it might be good practice to still do alt 2 to avoid someone with not as much react knowledge to come in and do something like:
export const useToken = (shouldUseCookieStore: boolean) => ({ value: shouldUseCookieStore ? useCookieStore(s => s.value) : useTokenStore(s => s.value) })
export const useToken = (shouldUseCookieStore: boolean) => ({ value: shouldUseCookieStore ? useCookieStore(s => s.value) : useTokenStore(s => s.value) })
Rather than
const useToken = (shouldUseCookieStore: boolean) => {
const value = useTokenStore(s => s.value)
const cookieValue = useCookieStore(s => s.value)
return { value: shouldUseCookieStore ? cookieValue : value }
}
const useToken = (shouldUseCookieStore: boolean) => {
const value = useTokenStore(s => s.value)
const cookieValue = useCookieStore(s => s.value)
return { value: shouldUseCookieStore ? cookieValue : value }
}
(psuedo code)
Josh
Josh13mo ago
Yeah that would be good advice hahaha
Fredrik
Fredrik13mo ago
👍 Thanks for your answer all the same! 🙏 And as long as you have the eslint rule the beginner would not be allowed to make the change above, so then it should be fine anyway
Want results from more Discord servers?
Add your server