May 29, 2024

Vercel Platforms Starter Kit infinite loop on editor page in nav.tsx

Fix bug in nav.tsx component

流逝之
by 流逝之
Vercel Platforms Starter Kit infinite loop on editor page in nav.tsx

Platforms Starter Kit has a lot of bugs,if you don't want to learn how to write nextjs code, forget Platforms Starter Kit, it is not friendly to newer.

like this bug in nav.tsx, an infinite loop on editor page

Let's look at the code, the problerm is in the component/nav.tsx file ,from line number 20 to line number 31:

const segments = useSelectedLayoutSegments();

The useEffect hook seems to be called whenever segments or id changes. If it keeps getting triggered, possible reasons include:

  1. State Update Causing a Loop: In the useEffect, you retrieve the id from getSiteFromPostId and set it with setSiteId. If this id affects the value of segments or id, it will cause a re-render every time the state updates, forming a loop.

  2. Frequent Changes in segments or id: If segments or id are props passed down from a parent component and these props frequently change in the parent component, it will cause this hook to trigger frequently.

  3. Unstable Reference Type Data: If segments is an array or object, even if the data hasn't changed significantly, any change in the reference address of the array or object will trigger useEffect. Ensure that the reference of segments passed from the outside remains the same when the data doesn't change.

The useSelectedLayoutSegments function always returns a new array object, even if the content is the same. Then, the useEffect hook will loop infinitely. The solution is very simple, using segments[0] instead of segments

Comments(0)


Scroll down to load more data.
Continue Reading