What could be causing the delay in scrolling when clicking on a React Router Link?

Having an issue with my React Nav bar. When a user clicks on it, it's supposed to scroll to a specific part of the page. However, there's a noticeable delay of about 1.5 seconds before the action takes place. Any suggestions on how to resolve this?

Here is the code for Navbar.js:

import React from "react";
import { Link } from 'react-scroll';
import { FaBars, FaTimes } from 'react-icons/fa';
import { useState, useEffect } from "react";
import '../styles/Navbar.css';

// More code here...

export default Navbar;

Also, here is the snippet from Navbar.css:

.header {
  // CSS styles here
}

// More CSS styles here...

Answer №1

Upon review, the main concern I have identified in this code is an unintended consequence. The code continuously adds a new scroll event listener each time the component re-renders without cleaning up any of them. This results in a growing workload, as it enqueues React state updates with each added listener. Given the intrusive nature of the scroll event, it likely leads to unnecessary and excessive work being generated.

To address this issue, consider moving the window.addEventListener logic into a useEffect hook and include a cleanup function to remove the event listener.

For instance:

const [fix, setFix] = useState(window.scrollY >= 950);

useEffect(() => {
  const setFixed = () => {
    setFix(window.scrollY >= 950);
  };

  window.addEventListener("scroll", setFixed);

  return () => {
    window.removeEventListener("scroll", setFixed);
  };
}, []);

Alternatively, you may opt to directly retrieve the window.scrollY value during rendering and bypass the need for the fix state and additional listeners altogether.

For example:

const fix = window?.scrollY >= 950;

return (
  <div className={fix ? 'header active' : 'header'}>
    <nav className={fix ? 'navbar fixed' : 'navbar'}>
      ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate the active class on the icon when hovering over a dynamically generated span using Vue

Is it possible to activate multiple music notes when hovering over one? For example, if I hover over music note 2, both note 1 and note 2 should get active classes. And if I hover over note 3, then all three spans/icons should become active. I have succes ...

When a value is deleted from an input in jQuery, all other changes become void

I am experiencing an issue with Javascript where even after deleting or changing the value of a field, jQuery effects still persist. Is there a way to reset all changes made when the input value is deleted? For example, you can visit , type 6 in and then ...

What is the mechanism behind the functionality of CSS @import?

Imagine I have created a class in my CSS, and this class is defined in 3 separate CSS files with different specifications... In the first CSS file, the width is set to 10px In the second CSS file, the width is changed to 20px Finally, in the third CSS f ...

Prevent the need to go through the keycloak callback process each time the page is

I have integrated keycloak as an identity provider into my React application. I successfully added the keycloak react dependency via npm. Below are the versions of the keycloak react npm modules on which my application depends : "@react-keycloak/web ...

Utilizing the .fadeOut('slow') method for CSS visibility manipulation

Here is a little JavaScript code snippet that I have: function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style. ...

Premature adjustment of images to window size changes

How can I make the images inside a divider move down when the right-end of the browser reaches them? Currently, they start moving down before the edge of the window is reached. Any suggestions on how to fix this? JSFIDDLE: https://jsfiddle.net/prtdaay1/2/ ...

Tips for troubleshooting and receiving error notifications when coding javascript/p5.js on Sublime text with a Flask backend

Currently, my web application project runs on a Flask backend within a virtual machine environment. I prefer using Sublime Text for coding, running Flask run command in the terminal, and accessing pages on http://127.0.0.1:5000/ via a web browser. Whenever ...

Aligning two divs vertically within another div without relying on the display:flex property

My goal is to align the content of two divs to the top within a parent div. I am unable to use display: flexbox, and it needs to be implemented as inline CSS. Currently, the layout appears as intended when the description div has only one line. However, i ...

Enhance your property by adding the isDirty feature

Managing changes to properties of classes in TypeScript can be optimized by tracking only the fields that have actually changed. Instead of using an array to keep track of property changes, I am exploring the idea of implementing an isDirty check. By incor ...

Data can be retrieved in a React/Next.js application when a button is clicked, even if the button is located in a separate

Whenever the button is clicked, my function fetches weather data for the current location. I am trying to figure out how to transfer this data from the Location component to the pages/index.tsx. This is where another component will display the data. This ...

The useParams() function encounters difficulty in converting data to number typescript

Whenever I try to convert the heroId type from string to number in my code, I always encounter an error. Here is the code snippet: import useHero from '../../hooks/useHero'; import {useParams} from 'react-router-dom' function Herospag ...

Enhance your website with a dynamic dropdown feature using Javascript and Bootstrap 5, allowing buttons to respond

Currently, I am experimenting with Javascript to dynamically incorporate elements into a Bootstrap 5 dropdown. To guide me, I referred to the relevant documentation which can be found here (https://getbootstrap.com/docs/5.0/components/dropdowns/#menu-items ...

Show the back button only if the user is not currently on the homepage

Is there a way to display a back button in the header when a user transitions from the homepage to the login page? .config(function($stateProvider, $urlRouterProvider,$ionicConfigProvider){ $ionicConfigProvider.tabs.position("standard"); $ioni ...

Leveraging Generic Types in React with TypeScript for Dynamically Assigning HTML Props based on Element Tags

I am frequently in need of a component that is essentially just a styled HTML tag. A good example is when I want to create beautifully styled div elements: // Definitions const styledDiv = (className: string) => { const StyledDiv = React.FC<HTMLA ...

Utilize JavaScript associative arrays to dynamically populate a dropdown menu, followed by automatically filling in a text

As a newcomer to Javascript (although I have a strong grasp of php), I'm experimenting with using associative arrays to accomplish two tasks. The first task is successfully populating a dropdown menu: var select = document.getElementById('FName ...

How can I use jQuery to locate all elements that match a specific style within the DOM?

Similar Question: How can I target hidden elements? Selecting multiple elements with CSS display:none property <div class="container"> <p style="display:none">I am hidden</p> <p>I am visible</p> <p>I am also ...

Is there a way to avoid getting a 404 error in Express when using multiple static directories?

I am working on serving files from two different folders to keep my admin and client content separate. The code I have set up initiates the two folders, but when Express looks for a file like example.css, it first checks the /static directory. If it doesn ...

Challenges encountered while entering text into the Discord message box using Selenium with Python

I've developed a program that automates the login process on Discord, navigates to a specified channel, and waits for a text channel to appear. Once the required text channel is visible, it clicks on the channel, inputs the command $claim, and hits en ...

Encountering a 'Cannot read property language of undefined' error while performing unit testing on next-i18next with the Link component and jest

next-i18next implements its own Link component to ensure compatibility with locale sub-paths. Check out the next-i18next GitHub repository here. During a simple snapshot test, I encountered the error message: Cannot read property language of undefined. ...

Utilize Three.js to trace user mouse clicks and project them onto the Fabric.js canvas being employed as the texture

I am currently working on creating a 3D product configurator. Initially, I import the .gltf model and render it using Three.js. Next, I generate an SVG onto a Fabric.js canvas and utilize that canvas to create a THREE.CanvasTexture, which is then used to ...