React Strict Mode - Second render, different initial state ?

[Next.js 14] I have a component that at the top of the function defines a Set of strings: const matches = new Set<string>() And then I do a bunch of loops and logic to add any matches that have been made prior, as I don't want any duplicate matches to be rendered further down in the code. Pretty straightforward. What confuses me, is that with ReactStrictMode on (as per default), I currently get 0 matches , when it renders a second time. And what also confuses me is that on the second render caused by strict mode, if I console log the values of the set right after where it's defined there seems to be an [[entries]] property as seen in the image below that are the values that should be in the set from the first render. Which seems to be the culprit, as I get exactly the right result of matches when I disable strict mode and only render once. I'm confused as to to why it would store the old values from the previous render, and cause the component to not work on following renders?
No description
8 Replies
dan
dan11mo ago
if I had to guess without seeing any code then you're probably doing the following
const [state,setState] = useState(new Set());
const [state,setState] = useState(new Set());
The problem here is that react avoids recreating inital state on rerenders (https://react.dev/reference/react/useState#avoiding-recreating-the-initial-state) The first render would inital the state, add the keys, and then get rerendered using the same Set object as the first render. You'd want to have a useEffect cleanup the removes all the keys from the set on unmouting the component.
useState – React
The library for web and native user interfaces
Grimbo
Grimbo11mo ago
No state, no useEffect, no hooks in the component itself.
dan
dan11mo ago
Then the set is outside react?
Grimbo
Grimbo11mo ago
export default function WikiContent({ blocks, pagesList, pageTitle }: WikiContentProps): React.JSX {
const matchedInternalLinks = new Set<string>()
export default function WikiContent({ blocks, pagesList, pageTitle }: WikiContentProps): React.JSX {
const matchedInternalLinks = new Set<string>()
dan
dan11mo ago
meaning it'll always be the same on every render
Grimbo
Grimbo11mo ago
Just defining a variable at the top of the function body that's empty. The component takes in a bunch of data, parses it, and returns JSX. No state required.
Josh
Josh11mo ago
Without seeing your code we are pretty much shooting in the dark on how to help you. I suggest giving more context https://imjosh.dev/blog/bad-questions
Bad Questions
An article by Josh
Josh
Josh11mo ago
And no, the 2 lines of code you have provided is not enough
Want results from more Discord servers?
Add your server