Optimize use fold hooks to trigger fewer re-renders

This commit is contained in:
James Grugett 2022-04-06 11:53:48 -05:00
parent 849248376b
commit dfa61be382
2 changed files with 12 additions and 6 deletions

View File

@ -34,9 +34,12 @@ export const useFolds = () => {
export const useFoldsWithTags = (tags: string[] | undefined) => {
const [folds, setFolds] = useState<Fold[] | undefined>()
const tagsKey = tags?.join(',')
useEffect(() => {
if (tags && tags.length > 0) return listenForFoldsWithTags(tags, setFolds)
}, [tags])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tagsKey])
return folds
}
@ -44,9 +47,12 @@ export const useFoldsWithTags = (tags: string[] | undefined) => {
export const useFollowingFold = (fold: Fold, user: User | null | undefined) => {
const [following, setFollowing] = useState<boolean | undefined>()
const foldId = fold?.id
const userId = user?.id
useEffect(() => {
if (user) return listenForFollow(fold, user, setFollowing)
}, [fold, user])
if (userId) return listenForFollow(foldId, userId, setFollowing)
}, [foldId, userId])
return following
}

View File

@ -148,11 +148,11 @@ export async function unfollowFoldFromSlug(slug: string, userId: string) {
}
export function listenForFollow(
fold: Fold,
user: User,
foldId: string,
userId: string,
setFollow: (following: boolean) => void
) {
const followDoc = doc(foldCollection, fold.id, 'followers', user.id)
const followDoc = doc(foldCollection, foldId, 'followers', userId)
return listenForValue(followDoc, (value) => {
setFollow(!!value)
})