2/n reduce react re-renders

This commit is contained in:
Igor Katson 2023-12-19 23:05:57 +00:00
parent e6ef3ff23f
commit 89bbcd2a27
No known key found for this signature in database
GPG key ID: B4EC22B66D61A3F5
7 changed files with 66 additions and 25 deletions

View file

@ -5,6 +5,7 @@ export interface TorrentStore {
torrents: Array<TorrentId> | null;
setTorrents: (torrents: Array<TorrentId>) => void;
torrentsInitiallyLoading: boolean;
torrentsLoading: boolean;
setTorrentsLoading: (loading: boolean) => void;
@ -12,11 +13,42 @@ export interface TorrentStore {
setRefreshTorrents: (callback: () => void) => void;
}
const torrentIdEquals = (t1: TorrentId, t2: TorrentId): boolean => {
return t1.id == t2.id && t1.info_hash == t2.info_hash;
};
const torrentsEquals = (t1: TorrentId[] | null, t2: TorrentId[] | null) => {
if (t1 === null && t2 === null) {
return true;
}
if (t1 === null || t2 === null) {
return false;
}
return (
t1.length === t2.length && t1.every((t, i) => torrentIdEquals(t, t2[i]))
);
};
export const useTorrentStore = create<TorrentStore>((set) => ({
torrents: null,
torrentsLoading: false,
setTorrentsLoading: (loading: boolean) => set({ torrentsLoading: loading }),
setTorrents: (torrents) => set({ torrents }),
torrentsInitiallyLoading: false,
setTorrentsLoading: (loading: boolean) =>
set((prev) => {
if (prev.torrents == null) {
return { torrentsInitiallyLoading: loading, torrentsLoading: loading };
}
return { torrentsInitiallyLoading: false, torrentsLoading: loading };
}),
setTorrents: (torrents) =>
set((prev) => {
if (torrentsEquals(prev.torrents, torrents)) {
return {};
}
return { torrents };
}),
refreshTorrents: () => {},
setRefreshTorrents: (callback) => set({ refreshTorrents: callback }),
}));