Skip to content

Map Glitches Due to Unnecessary Re-Renders#1156

Merged
kasya merged 42 commits intoOWASP:mainfrom
srinjoy933:srinjoy933/issue-1128
Apr 20, 2025
Merged

Map Glitches Due to Unnecessary Re-Renders#1156
kasya merged 42 commits intoOWASP:mainfrom
srinjoy933:srinjoy933/issue-1128

Conversation

@srinjoy933
Copy link
Copy Markdown
Contributor

@srinjoy933 srinjoy933 commented Mar 22, 2025

Resolves #1128

Optimized marker management using clearLayers() instead of re-adding markers.

Ensured single map initialization with useEffect.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 22, 2025

Summary by CodeRabbit

  • Refactor
    • Streamlined the way markers are updated and grouped on the interactive map to improve performance and responsiveness.

Walkthrough

The pull request refactors the marker cluster logic in the ChapterMap component. The code now conditionally initializes the marker cluster group and, if already set, clears its layers instead of removing and re-adding markers individually. Additionally, marker creation is refactored to generate an array using the map function and add all markers in a single operation, streamlining the update process and reducing direct manipulations on the map layers.

Changes

File(s) Change Summary
frontend/.../ChapterMap.tsx Refactored marker cluster handling: conditionally initializes the cluster group, clears existing layers instead of full removal, and uses map for batch marker creation.

Assessment against linked issues

Objective Addressed Explanation
Optimize map marker management to prevent unnecessary re-renders (#1128)

Suggested reviewers

  • arkid15r

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73706ee and 0c2d46f.

📒 Files selected for processing (1)
  • frontend/src/components/ChapterMap.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/components/ChapterMap.tsx

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
frontend/src/components/ChapterMap.tsx (3)

34-47: Consider extracting map configuration to constants.

While the current implementation is correct, the map configuration could be extracted to named constants for better readability and maintainability.

+const DEFAULT_MAP_VIEW = [20, 0];
+const DEFAULT_ZOOM_LEVEL = 2;
+const MAP_BOUNDS = [[-90, -180], [90, 180]];
+const TILE_LAYER_URL = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
+const TILE_LAYER_ATTRIBUTION = '© OpenStreetMap contributors';

useEffect(() => {
  if (!mapRef.current) {
    const map = L.map('chapter-map', {
      worldCopyJump: false,
      maxBounds: MAP_BOUNDS,
      maxBoundsViscosity: 1.0,
-    }).setView([20, 0], 2)
+    }).setView(DEFAULT_MAP_VIEW, DEFAULT_ZOOM_LEVEL)

-    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
-      attribution: '© OpenStreetMap contributors',
+    L.tileLayer(TILE_LAYER_URL, {
+      attribution: TILE_LAYER_ATTRIBUTION,
      className: 'map-tiles',
    }).addTo(map)

67-88: Consider extracting marker creation into a separate function.

The marker creation logic could be extracted into a separate function for better code organization and testability.

+const createMarker = (chapter) => {
+  const markerIcon = new L.Icon({
+    iconAnchor: [12, 41],
+    iconRetinaUrl: '/img/marker-icon-2x.png',
+    iconSize: [25, 41],
+    iconUrl: '/img/marker-icon.png',
+    popupAnchor: [1, -34],
+    shadowSize: [41, 41],
+    shadowUrl: '/img/marker-shadow.png',
+  });
+
+  const marker = L.marker([chapter.lat, chapter.lng], { icon: markerIcon }).bindPopup(
+    `<div class="popup-content">${chapter.name}</div>`
+  );
+
+  marker.on('click', () => {
+    window.location.href = `/chapters/${chapter.key}`;
+  });
+
+  return marker;
+};

// In the updateMarkers function:
chapters.forEach((chapter) => {
-  const markerIcon = new L.Icon({
-    iconAnchor: [12, 41],
-    iconRetinaUrl: '/img/marker-icon-2x.png',
-    iconSize: [25, 41],
-    iconUrl: '/img/marker-icon.png',
-    popupAnchor: [1, -34],
-    shadowSize: [41, 41],
-    shadowUrl: '/img/marker-shadow.png',
-  });
-
-  const marker = L.marker([chapter.lat, chapter.lng], { icon: markerIcon }).bindPopup(
-    `<div class="popup-content">${chapter.name}</div>`
-  );
-
-  marker.on('click', () => {
-    window.location.href = `/chapters/${chapter.key}`;
-  });
+  const marker = createMarker(chapter);

  markerClusterGroup.addLayer(marker);
  bounds.push([chapter.lat, chapter.lng]);
});

68-77: Consider using useMemo for the marker icon.

The marker icon configuration is recreated for each marker but remains constant. Consider using useMemo to create it once.

+// Create marker icon once
+const markerIcon = useMemo(() => new L.Icon({
+  iconAnchor: [12, 41],
+  iconRetinaUrl: '/img/marker-icon-2x.png',
+  iconSize: [25, 41],
+  iconUrl: '/img/marker-icon.png',
+  popupAnchor: [1, -34],
+  shadowSize: [41, 41],
+  shadowUrl: '/img/marker-shadow.png',
+}), []);

// In the updateMarkers function:
chapters.forEach((chapter) => {
-  const markerIcon = new L.Icon({
-    iconAnchor: [12, 41],
-    iconRetinaUrl: '/img/marker-icon-2x.png',
-    iconSize: [25, 41],
-    iconUrl: '/img/marker-icon.png',
-    popupAnchor: [1, -34],
-    shadowSize: [41, 41],
-    shadowUrl: '/img/marker-shadow.png',
-  });

  const marker = L.marker([chapter.lat, chapter.lng], { icon: markerIcon })...
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 64abd88 and d660ad6.

📒 Files selected for processing (1)
  • frontend/src/components/ChapterMap.tsx (5 hunks)
🔇 Additional comments (9)
frontend/src/components/ChapterMap.tsx (9)

2-2: Properly added React hooks imports.

The addition of useMemo and useCallback imports is correct and necessary for the performance optimizations made in this component.


21-21: Clear comment indicating purpose of useMemo.

Good practice to add explanatory comments for React hooks usage.


31-50: Improved map initialization pattern.

The map initialization has been properly isolated in its own effect with an empty dependency array to ensure it only runs once. Creating a local map variable before assigning to the ref improves code clarity.


52-53: Informative comment for the new updateMarkers function.

The comment clearly explains the purpose of this function which helps with maintainability.


53-101: Effective use of useCallback for optimization.

Good implementation of useCallback to memoize the updateMarkers function with the correct dependencies [chapters, showLocal]. This prevents unnecessary function recreations during re-renders, directly addressing the PR objective of reducing map glitches.


57-63: Optimized marker management.

The new approach of clearing existing layers instead of recreating the marker cluster group is more efficient. The conditional logic properly handles both the initial case and subsequent updates.


78-80: Simplified popup binding.

The refactored popup creation using bindPopup directly with a template string makes the code more concise and readable.


95-95: Streamlined local chapters selection.

The modified slice operation more directly expresses the intent to include the maximum number of nearest chapters.


103-106: Proper effect for marker updates.

The new effect correctly triggers the updateMarkers function when its dependencies change. This separation of concerns improves code organization and ensures markers are updated when needed.

Comment thread frontend/src/components/ChapterMap.tsx
Comment thread frontend/src/components/ChapterMap.tsx Outdated
`<div class="popup-content">${chapter.name}</div>`
)

marker.on('click', () => {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't change the map behavior on the first click to the marker.
On the first click, it should display a popup with the chapter name, and only on the second click to the name should it redirect to that specific chapter.

Copy link
Copy Markdown
Contributor

@Dishant1804 Dishant1804 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall the useMemo and useCallback hook will improve the performance and avoid unnecessary re renders. please make the suggested changes
Thank you :)

Comment thread frontend/src/components/ChapterMap.tsx Outdated
const nearestChapter = chapters[0]
map.setView([nearestChapter.lat, nearestChapter.lng], maxZoom)
map.fitBounds(localBounds, { maxZoom: maxZoom })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

map.fitBounds() does not ensure that the nearest chapter gets focused first before fitting bounds, this will lead to unexpected zoom behavior, because the setView() is removed which was responsible for setting the initial zoomed view on nearest chapter.
Please fix it @srinjoy933

Comment thread frontend/src/components/ChapterMap.tsx Outdated
// Create a new marker cluster group
const markerClusterGroup = L.markerClusterGroup()
// Clear existing markers if needed
if (markerClusterRef.current) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

handle the condition where the markerClusterRef.current is null, because if the previous markers are not cleared properly this may lead to duplicate markers while re rendering.

Comment thread frontend/src/components/ChapterMap.tsx Outdated
}))
}, [geoLocData])

// Function to initialize map (runs once)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please remove all the comments from the file they are not necessary here :)

Copy link
Copy Markdown
Contributor

@Rajgupta36 Rajgupta36 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree with @abhayymishraa and @Dishant1804 comments. Try not to store tiles in the cache, as it can severely impact memory usage. This is a world map, not just for a specific place.

@abhayymishraa
Copy link
Copy Markdown
Contributor

Agree with @Rajgupta36 and @Dishant1804 Storing cache will lead here to memory leak because Leaflet fetches images according to the zoom

@srinjoy933
Copy link
Copy Markdown
Contributor Author

thanks @abhayymishraa , @Dishant1804 , @Rajgupta36 for the suggestions . i will make the changes and come with the updated one

@srinjoy933
Copy link
Copy Markdown
Contributor Author

@abhayymishraa , @Dishant1804 , @Rajgupta36 can you please review this and tell me ,is there any changes required .thank you.

Comment thread frontend/src/components/ChapterMap.tsx Outdated
Comment on lines +81 to +87
let clicked = false
popupContent.addEventListener('click', () => {
if (clicked) {
window.location.href = `/chapters/${chapter.key}`
}
clicked = true
setTimeout(() => (clicked = false), 500)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I mentioned earlier, please check out Nest-Chapters.
When you click on a marker a tooltip appears. Clicking on the name inside the tooltip then it redirects you to that chapter.
We need this same behaviour as this task is for optimizing the re-renders.

Comment thread frontend/src/components/ChapterMap.tsx Outdated
Comment on lines 81 to 88
let clicked = false
popupContent.addEventListener('click', () => {
if (clicked) {
window.location.href = `/chapters/${chapter.key}`
}
clicked = true
setTimeout(() => (clicked = false), 500)
})
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let clicked = false
popupContent.addEventListener('click', () => {
if (clicked) {
window.location.href = `/chapters/${chapter.key}`
}
clicked = true
setTimeout(() => (clicked = false), 500)
})
popupContent.addEventListener('click', () => {
window.location.href = `/chapters/${chapter.key}`
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can use the previous logic it will work fine

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks @abhayymishraa for your suggestions, i have made the changes according to what you have said, can you review that once. thank you

Copy link
Copy Markdown
Contributor

@Rajgupta36 Rajgupta36 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work @srinjoy933 👍

@srinjoy933 srinjoy933 requested a review from kasya March 31, 2025 14:33
@srinjoy933
Copy link
Copy Markdown
Contributor Author

@arkid15r , @kasya any update for me regarding this pr

Comment thread .pre-commit-config.yaml Outdated
- --offset=2
- --sequence=4
exclude: (.github|frontend/pnpm-lock.yaml)
exclude: (.github|frontend/pnpm-lock.yaml|^\.pre-commit-config\.yaml$)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@srinjoy933 why this change? 🤔 Can we keep it as before? The rest looks good and ready to go!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ kasya can we make it same.as it will not hamper any other such hooks.but due to that hook only many a times test fails ,due to that reason i made it exclude that particular file only ,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i myself faced problem in the code quality tests, so i excluded it for that file only. will it be okay to make it there, as it dont hamper in any other cases

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kasya will it be okay for you?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@srinjoy933 it doesn't seem to be the problem for other contributors though. 🤔
If you're not sure how to make it not fail the tests you can always ask in our Slack channel for guidance from other contributors.

@srinjoy933 srinjoy933 requested a review from kasya April 3, 2025 02:46
@srinjoy933
Copy link
Copy Markdown
Contributor Author

i solved the issue and now i think it is ready to merge. @kasya is it fine now?

Copy link
Copy Markdown
Collaborator

@kasya kasya left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Works great! 👍🏼

@sonarqubecloud
Copy link
Copy Markdown

@kasya kasya enabled auto-merge April 20, 2025 17:23
@srinjoy933 srinjoy933 requested a review from kasya April 20, 2025 19:40
@kasya kasya added this pull request to the merge queue Apr 20, 2025
Merged via the queue into OWASP:main with commit 0af1ad6 Apr 20, 2025
22 checks passed
shdwcodr pushed a commit to shdwcodr/Nest that referenced this pull request Jun 5, 2025
* changes for the issue-1128

* updated

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update ChapterMap.tsx

* Update .pre-commit-config.yaml

* Update ChapterMap.tsx

* Update .pre-commit-config.yaml

* your commit message

---------

Co-authored-by: Arkadii Yakovets <2201626+arkid15r@users.noreply.github.com>
Co-authored-by: Kate Golovanova <kate@kgthreads.com>
@coderabbitai coderabbitai Bot mentioned this pull request Dec 26, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Map Glitches Due to Unnecessary Re-Renders

6 participants