Skip to content

Commit

Permalink
Merge pull request #713 from ephemeraHQ/noe/perf-rerenders-optimizati…
Browse files Browse the repository at this point in the history
…ons-v2

Fix conversation context, remove unused dependencies
  • Loading branch information
saulmc authored Sep 11, 2024
2 parents 5d6920b + 813d54c commit 4c54dd8
Show file tree
Hide file tree
Showing 16 changed files with 72 additions and 84 deletions.
5 changes: 1 addition & 4 deletions components/Chat/Attachment/AddAttachmentButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ export default function AddAttachmentButton({
onSelectionStatusChange,
}: AddAttachmentButtonProps) {
const colorScheme = useColorScheme();
const { mediaPreviewRef } = useConversationContext([
"conversation",
"mediaPreviewRef",
]);
const mediaPreviewRef = useConversationContext("mediaPreviewRef");
const currentAccount = useAccountsStore((s) => s.currentAccount);

const styles = useStyles();
Expand Down
22 changes: 6 additions & 16 deletions components/Chat/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,21 +173,12 @@ const getListArray = (
};

export default function Chat() {
const {
conversation,
isBlockedPeer,
onReadyToFocus,
transactionMode,
frameTextInputFocused,
onPullToRefresh,
} = useConversationContext([
"conversation",
"isBlockedPeer",
"onReadyToFocus",
"transactionMode",
"frameTextInputFocused",
"onPullToRefresh",
]);
const conversation = useConversationContext("conversation");
const isBlockedPeer = useConversationContext("isBlockedPeer");
const onReadyToFocus = useConversationContext("onReadyToFocus");
const transactionMode = useConversationContext("transactionMode");
const frameTextInputFocused = useConversationContext("frameTextInputFocused");

const xmtpAddress = useCurrentAccount() as string;
const peerSocials = useProfilesStore(
useShallow((s) =>
Expand Down Expand Up @@ -386,7 +377,6 @@ export default function Chat() {
<AnimatedListView
contentContainerStyle={styles.chat}
data={listArray}
onRefresh={onPullToRefresh}
refreshing={conversation?.pending}
extraData={[peerSocials]}
renderItem={renderItem}
Expand Down
5 changes: 3 additions & 2 deletions components/Chat/ChatPlaceholder/ChatPlaceholder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ type Props = {
};

export default function ChatPlaceholder({ messagesCount }: Props) {
const { conversation, isBlockedPeer, onReadyToFocus } =
useConversationContext(["conversation", "isBlockedPeer", "onReadyToFocus"]);
const conversation = useConversationContext("conversation");
const isBlockedPeer = useConversationContext("isBlockedPeer");
const onReadyToFocus = useConversationContext("onReadyToFocus");
const colorScheme = useColorScheme();
const styles = useStyles();
const setPeersStatus = useSettingsStore((s) => s.setPeersStatus);
Expand Down
13 changes: 3 additions & 10 deletions components/Chat/ChatPlaceholder/GroupChatPlaceholder.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useGroupConsent } from "@hooks/useGroupConsent";
import { useGroupMembers } from "@hooks/useGroupMembers";
import { useGroupName } from "@hooks/useGroupName";
import { translate } from "@i18n";
Expand Down Expand Up @@ -26,24 +25,18 @@ type Props = {
};

export function GroupChatPlaceholder({ messagesCount }: Props) {
const { conversation, onReadyToFocus } = useConversationContext([
"conversation",
"isBlockedPeer",
"onReadyToFocus",
]);
const conversation = useConversationContext("conversation");
const onReadyToFocus = useConversationContext("onReadyToFocus");

const currentAccount = useCurrentAccount();
const { data: group } = useGroupQuery(
currentAccount ?? "",
conversation?.topic ?? ""
);
const { consent } = useGroupConsent(conversation?.topic ?? "");
const { groupName } = useGroupName(conversation?.topic ?? "");
const { members } = useGroupMembers(conversation?.topic ?? "");
const isBlockedGroup = consent === "denied";

const colorScheme = useColorScheme();
const styles = useStyles();
const { allowGroup } = useGroupConsent(conversation?.topic ?? "");
const groupCreatedByUser = useMemo(() => {
if (!group || !currentAccount) {
return false;
Expand Down
6 changes: 2 additions & 4 deletions components/Chat/ConsentPopup/ConsentPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,8 @@ import Button from "../../Button/Button";
import { showActionSheetWithOptions } from "../../StateHandlers/ActionSheetStateHandler";

export default function ConsentPopup() {
const { conversation, isBlockedPeer } = useConversationContext([
"conversation",
"isBlockedPeer",
]);
const conversation = useConversationContext("conversation");
const isBlockedPeer = useConversationContext("isBlockedPeer");

const navigation = useNavigation() as NativeStackNavigationProp<
NavigationParamList,
Expand Down
2 changes: 1 addition & 1 deletion components/Chat/ConsentPopup/GroupConsentPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import Button from "../../Button/Button";
import { showActionSheetWithOptions } from "../../StateHandlers/ActionSheetStateHandler";

export function GroupConsentPopup() {
const { conversation } = useConversationContext(["conversation"]);
const conversation = useConversationContext("conversation");

const navigation = useNavigation() as NativeStackNavigationProp<
NavigationParamList,
Expand Down
15 changes: 7 additions & 8 deletions components/Chat/Frame/FramePreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
handleTxAction,
validateFrame,
} from "../../../utils/frames";
import { navigate } from "../../../utils/navigation";
import { MessageToDisplay } from "../Message/Message";

export default function FramePreview({
Expand All @@ -35,10 +34,10 @@ export default function FramePreview({
message: MessageToDisplay;
}) {
const styles = useStyles();
const { conversation, setFrameTextInputFocused } = useConversationContext([
"conversation",
"setFrameTextInputFocused",
]);
const conversation = useConversationContext("conversation");
const setFrameTextInputFocused = useConversationContext(
"setFrameTextInputFocused"
);
const account = useCurrentAccount() as string;
const [postingActionForButton, setPostingActionForButton] = useState(
undefined as undefined | number
Expand Down Expand Up @@ -286,9 +285,9 @@ export default function FramePreview({
]
);

const shareFrame = useCallback(() => {
navigate("ShareFrame", { frameURL: initialFrame.url });
}, [initialFrame.url]);
// const shareFrame = useCallback(() => {
// navigate("ShareFrame", { frameURL: initialFrame.url });
// }, [initialFrame.url]);

const showBottom =
(frame.type === "PREVIEW" && frame.extractedTags["og:title"]) ||
Expand Down
21 changes: 6 additions & 15 deletions components/Chat/Input/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,21 +77,12 @@ interface ChatInputProps {
}

export default function ChatInput({ inputHeight }: ChatInputProps) {
const {
conversation,
inputRef,
transactionMode,
messageToPrefill,
mediaPreviewRef,
mediaPreviewToPrefill,
} = useConversationContext([
"conversation",
"inputRef",
"messageToPrefill",
"mediaPreviewRef",
"mediaPreviewToPrefill",
"transactionMode",
]);
const conversation = useConversationContext("conversation");
const inputRef = useConversationContext("inputRef");
const transactionMode = useConversationContext("transactionMode");
const messageToPrefill = useConversationContext("messageToPrefill");
const mediaPreviewRef = useConversationContext("mediaPreviewRef");
const mediaPreviewToPrefill = useConversationContext("mediaPreviewToPrefill");

const colorScheme = useColorScheme();
const styles = useStyles();
Expand Down
16 changes: 11 additions & 5 deletions components/Chat/Message/MessageReactions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import {
useCurrentAccount,
useProfilesStore,
} from "../../../data/store/accountsStore";
import { useConversationContext } from "../../../utils/conversation";
import { getPreferredAvatar, getPreferredName } from "../../../utils/profile";
import {
MessageReaction,
Expand All @@ -47,7 +46,6 @@ type ReactionCount = {
};

function ChatMessageReactions({ message, reactions }: Props) {
const { conversation } = useConversationContext(["conversation"]);
const colorScheme = useColorScheme();
const styles = useStyles();
const userAddress = useCurrentAccount();
Expand Down Expand Up @@ -99,15 +97,15 @@ function ChatMessageReactions({ message, reactions }: Props) {

const handleReactionPress = useCallback(
(reaction: ReactionCount) => {
if (!conversation || !userAddress) return;
if (!userAddress) return;

if (reaction.userReacted) {
removeReactionFromMessage(userAddress, message, reaction.content);
} else {
addReactionToMessage(userAddress, message, reaction.content);
}
},
[conversation, message, userAddress]
[message, userAddress]
);

if (reactionsList.length === 0) return null;
Expand Down Expand Up @@ -190,7 +188,15 @@ function ChatMessageReactions({ message, reactions }: Props) {
);
}

export default memo(ChatMessageReactions);
export default memo(ChatMessageReactions, (prevProps, nextProps) => {
if (prevProps.message.id !== nextProps.message.id) {
return false;
}
if (prevProps.message.lastUpdateAt !== nextProps.message.lastUpdateAt) {
return false;
}
return true;
});

const useStyles = () => {
const colorScheme = useColorScheme();
Expand Down
2 changes: 1 addition & 1 deletion components/Chat/Transaction/SendMoneyButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { executeAfterKeyboardClosed } from "../../../utils/keyboard";
import ActionButton from "../ActionButton";

export default function SendMoneyButton() {
const { setTransactionMode } = useConversationContext(["setTransactionMode"]);
const setTransactionMode = useConversationContext("setTransactionMode");
const { setAddingNewAccount, setConnectionMethod } = useOnboardingStore(
useSelect(["setAddingNewAccount", "setConnectionMethod"])
);
Expand Down
10 changes: 4 additions & 6 deletions components/Chat/Transaction/TransactionInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,10 @@ import ActionButton from "../ActionButton";

export default function TransactionInput() {
const USDCBalance = useWalletStore((s) => s.USDCBalance);
const { conversation, setTransactionMode, transactionMode } =
useConversationContext([
"conversation",
"setTransactionMode",
"transactionMode",
]);
const conversation = useConversationContext("conversation");
const setTransactionMode = useConversationContext("setTransactionMode");
const transactionMode = useConversationContext("transactionMode");

const privySigner = usePrivySigner();

const colorScheme = useColorScheme();
Expand Down
2 changes: 1 addition & 1 deletion components/Chat/Transaction/TransactionPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ const TransactionStatusView = ({
export default function TransactionPreview({ message }: Props) {
const colorScheme = useColorScheme();
const styles = useStyles();
const { conversation } = useConversationContext(["conversation"]);
const conversation = useConversationContext("conversation");
const { transaction, transactionDisplay, amountToDisplay } =
useTransactionForMessage(message, conversation?.peerAddress);

Expand Down
2 changes: 0 additions & 2 deletions components/Recommendations/Recommendations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {
View,
useColorScheme,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

import { Recommendation } from "./Recommendation";
import config from "../../config";
Expand Down Expand Up @@ -65,7 +64,6 @@ export default function Recommendations({
"updatedAt",
])
);
const insets = useSafeAreaInsets();
const styles = useStyles();

const openSignalList = useCallback(() => {
Expand Down
9 changes: 4 additions & 5 deletions containers/EmojiPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { useSelect } from "@data/store/storeHelpers";
import { textSecondaryColor } from "@styles/colors";
import { useConversationContext } from "@utils/conversation";
import { emojis } from "@utils/emojis/emojis";
import { favoritedEmojis } from "@utils/emojis/favoritedEmojis";
import { CategorizedEmojisRecord, Emoji } from "@utils/emojis/interfaces";
import {
addReactionToMessage,
Expand Down Expand Up @@ -46,9 +45,9 @@ const sliceEmojis = (emojis: Emoji[]) => {
return slicedEmojis;
};

const myEmojis = sliceEmojis(
flatEmojis.filter((emoji) => favoritedEmojis.isFavorite(emoji.emoji))
);
// const myEmojis = sliceEmojis(
// flatEmojis.filter((emoji) => favoritedEmojis.isFavorite(emoji.emoji))
// );

export const EmojiPicker = ({ message }: { message: MessageToDisplay }) => {
const currentUser = useCurrentAccount() as string;
Expand Down Expand Up @@ -91,7 +90,7 @@ export const EmojiPicker = ({ message }: { message: MessageToDisplay }) => {
setReactMenuMessageId(null);
setSearchInput("");
}, [setReactMenuMessageId]);
const { conversation } = useConversationContext(["conversation"]);
const conversation = useConversationContext("conversation");
const handleReaction = useCallback(
(emoji: string) => {
if (!conversation) return;
Expand Down
6 changes: 2 additions & 4 deletions utils/conversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { getAddressForPeer } from "./eth";
import { getGroupIdFromTopic } from "./groupUtils/groupId";
import logger from "./logger";
import { subscribeToNotifications } from "./notifications";
import { pick } from "./objects";
import { getReactionsContentPreview } from "./reactions";
import { getMatchedPeerAddresses } from "./search";
import { sentryTrackMessage } from "./sentry";
Expand Down Expand Up @@ -275,7 +274,6 @@ export type ConversationContextType = {
setTransactionMode: (b: boolean) => void;
frameTextInputFocused: boolean;
setFrameTextInputFocused: (b: boolean) => void;
onPullToRefresh?: () => void;
};

export const ConversationContext = createContext<ConversationContextType>({
Expand All @@ -293,8 +291,8 @@ export const ConversationContext = createContext<ConversationContextType>({
});

export const useConversationContext = <K extends keyof ConversationContextType>(
keys: K[]
) => useContextSelector(ConversationContext, (s) => pick(s, keys));
key: K
) => useContextSelector(ConversationContext, (s) => s[key]);

const conversationsSortMethod = (
a: ConversationWithLastMessagePreview,
Expand Down
20 changes: 20 additions & 0 deletions utils/debug.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { useEffect } from "react";

import logger from "./logger";

const timestamps: { [timestampId: string]: { start: number; last: number } } =
Expand Down Expand Up @@ -36,3 +38,21 @@ export const debugTimeSpent = ({
}
}
};

const componentRenderCount: {
[componentName: string]: { total: number; byId: { [id: string]: number } };
} = {};

export const useLogRenderCount = (componentName: string, id: string) => {
useEffect(() => {
componentRenderCount[componentName] = componentRenderCount[
componentName
] || { total: 0, byId: {} };
componentRenderCount[componentName].total += 1;
componentRenderCount[componentName].byId[id] =
(componentRenderCount[componentName].byId[id] || 0) + 1;
logger.warn(
`${componentName} rendered - for ${id} ${componentRenderCount[componentName].byId[id]} - total ${componentRenderCount[componentName].total}`
);
});
};

0 comments on commit 4c54dd8

Please sign in to comment.