Problem: When updating the state in MobX or calling a mutation in SWR, all components are being re-rendered, although I want to update only one element.
Example code:
In the React sandbox, rendering occurs twice when selecting an element (likely due to StrictMode):
[Link to React sandbox]
In the Next.js sandbox, rendering occurs five times when selecting an element:
[Link to Next.js sandbox]
I’ve tried calling mutate when selecting a post and adding the active property to determine whether the element is active or not. However, this approach didn’t help. Moreover, it doesn’t fully solve my problem because if I navigate to another section where the same post exists, it won’t be highlighted.
What I want to achieve: When selecting an element (for example, a post), it is stored globally and highlighted. If the user navigates to other sections (without selecting a new post), upon returning to the section with the selected post, it continues to be highlighted. This functionality resembles what’s found in music players, where selecting a track triggers an animation, and when returning to the section, the animation persists, allowing the user to pause it.
I also have an idea to add a unique identifier to each element and then search for it in the DOM tree to change it specifically. However, I’m not sure if this is the right approach and whether it’s even worth trying to implement.
I would be grateful for any help or recommendations to solve this problem!
I am using:
Next.js 14.2.3
React 18
SWR 2.2.5
MobX 6.12.3
mobx-react-lite 4.0.7