From ba4111c9ef94168cc2b0b10345c3629ac1bdbd6f Mon Sep 17 00:00:00 2001 From: zaidmukaddam Date: Thu, 8 Aug 2024 22:59:16 +0530 Subject: [PATCH] fix: Maximum update depth exceeded --- app/page.tsx | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/app/page.tsx b/app/page.tsx index a03fdb2..89374f4 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,7 +1,7 @@ /* eslint-disable @next/next/no-img-element */ "use client"; -import React, { useRef, useCallback, useState, useEffect, ReactNode } from 'react'; +import React, { useRef, useCallback, useState, useEffect, ReactNode, useMemo } from 'react'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; import { useChat } from 'ai/react'; @@ -134,17 +134,21 @@ export default function Home() { ); }; - const CitationComponent: React.FC<{ href: string; children: ReactNode; index: number }> = ({ href, children, index }) => { + const CitationComponent: React.FC<{ href: string; children: ReactNode; index: number }> = React.memo(({ href, children, index }) => { const citationText = Array.isArray(children) ? children[0] : children; return renderCitation(citationText as string, href, index); - }; + }); - const MarkdownRenderer: React.FC<{ content: string }> = ({ content }) => { - const citationLinks = [...content.matchAll(/\[([^\]]+)\]\(([^)]+)\)/g)].map(([_, text, link]) => ({ - text, - link, - })); + CitationComponent.displayName = "CitationComponent"; + + const MarkdownRenderer: React.FC<{ content: string }> = React.memo(({ content }) => { + const citationLinks = useMemo(() => { + return [...content.matchAll(/\[([^\]]+)\]\(([^)]+)\)/g)].map(([_, text, link]) => ({ + text, + link, + })); + }, [content]); // Recompute only if content changes return ( { - const index = citationLinks.findIndex(link => link.link === href); + const index = citationLinks.findIndex((link: { link: string | undefined; }) => link.link === href); return index !== -1 ? ( - + {children} ) : ( @@ -168,7 +172,9 @@ export default function Home() { {content} ); - }; + }); + + MarkdownRenderer.displayName = "MarkdownRenderer"; useEffect(() => { if (bottomRef.current) {