Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
Delay after prepending elements to a list and scroll to same scrolling view

When you scroll to some position in the list and press "Space", new elements are prepended to the list. The code intention is to stay in the same scrolling view as before the user press "Space." Items are loaded and for some miliseconds, scroll view is in top of new prepended items and then scroll to saved previous scroll view. I want to make it instantly, without that miliseconds delay that is annoying for user.

Is it possible to get it?

CODE:

import React, { useState, useEffect, useRef } from "react";
import "./styles.css";

export default function App() {
  const listRefs = useRef({});
  const scrollRef = useRef();
  const oldListHeight = useRef();

  const generateId = (length) => {
    let result = "";
    const characters =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    const charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
  };

  const generateList = () => {
    const html = [];

    for (let i = 0; i < Math.floor(Math.random() * 30) + 20; i++) {
      const id = generateId(15);

      listRefs.current[id] = React.createRef();
      html.push(
        <li ref={listRefs[id]} key={id}>
          {id}
        </li>
      );
    }

    return html;
  };

  const [htmlList, setHtmlList] = useState(generateList());

  useEffect(() => {
    setTimeout(() => {
      const listHeightDiff =
        scrollRef.current.scrollHeight - oldListHeight.current;
      scrollRef.current.scrollTo({
        top: scrollRef.current.scrollTop + listHeightDiff
      });
    }, 0);
  }, [htmlList]);

  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown, false);

    return () => {
      window.removeEventListener("keydown", handleKeyDown, false);
    };
  }, []);

  const handleKeyDown = (e) => {
    if (e.key === " ") {
      oldListHeight.current = scrollRef.current.scrollHeight;
      setHtmlList((htmlList) => [generateList(), ...htmlList]);
    }
  };

  return (
    <div className="App">
      <div ref={scrollRef} className="wrapper">
        <ul>{htmlList}</ul>
      </div>
    </div>
  );
}

PLAYGROUND:

https://codesandbox.io/s/affectionate-antonelli-wkvvd?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think this is the issue,

Your setHtmlList((htmlList) => [generateList(), ...htmlList]);

generateList() returns an array so your array becomes [[some ids],oldids],

It becomes an array of arrays and React re-renders everything. What you need is [new ids,old ids].

To fix it I had to change the above line to

setHtmlList((htmlList) => [...generateList(), ...htmlList]);

Note the spread operator on generateList(). That will make the array flat and React can manage the rest.

Updated code,

https://codesandbox.io/s/eloquent-cherry-6hxyo?file=/src/App.js:1572-1633

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!