Enhance the speed of filtering a large array of 4000+ objects in React for optimal performance

I am currently dealing with a component that generates an input of type text for filtering an array containing over 4000 objects.

 const { airports } = useContext(MainContext);
 const [airportListLocal, setAirportListLocal] = useState<Airport[]>(airports);

 useEffect(() => {
    setAirportListLocal(airports);
  }, []);

The airports variable holds a significantly large array of objects, retrieved initially through the useContext. To prevent altering the original airports array, I store it in the local state as (airportListLocal). However, I suspect this approach may be contributing to the performance issues.

<input
    type="text"
    name="From"
    className="w-full border rounded-xl h-11 p-4 text-sm focus:border-blue-500 outline-none focus-border-2"
    placeholder="Start your flight search"
    onKeyDown={(e) => searchAirports(e)}
    onChange={(e) => checkIfEmpty(e)}
  />

The onKeyDown function is utilized to detect when the user finishes typing and hits enter.

  const searchAirports = (e: React.KeyboardEvent) => {
    const searchValue = (e.target as HTMLInputElement).value.toLowerCase();

    if (e.key === "Enter") {
      const filteredAirports = airportListLocal.filter(
        (airport) =>
          airport.name.toLowerCase().includes(searchValue) ||
          airport.country.toLowerCase().includes(searchValue) ||
          airport.city.toLowerCase().includes(searchValue)
      );
      setAirportListLocal(filteredAirports);
    }
  };

The onChange function serves to determine if there is no input, indicating that the user hasn't typed anything or has deleted all entries to display all results.

  const checkIfEmpty = (e: React.FormEvent) => {
    if ((e.target as HTMLInputElement).value.length === 0) {
      setAirportListLocal(airports);
    }
  };

To render the data, I map over the current state like so:

<div className="airports-list mt-8 search-results-airports h-28 overflow-y-scroll scroll">
    {airportListLocal.map((airport) => (
      <div key={airport.id} className="flex justify-between">
        <p className="font-bold text-sm">{airport.country}</p>
        <p className="text-xs">{airport.name}</p>
      </div>
    ))}
  </div>

Issue: The application's performance is extremely poor. It's unreasonably slow. Upon component mounting, Chrome even becomes unresponsive. Typing a single character in the input causes the app to freeze yet again.

I'm struggling to pinpoint the root cause of these performance woes. I'm unable to control the API providing the data, hence unable to fetch a paginated version. All data comes in a single load.

Any insights or suggestions?

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

What's the best way to establish a victorious player in a game of Tic

I've been struggling to find a solution for determining the winner using WinCombos. Is there a way to compare the elements in my winCombos array with the cells of a 3x3 tic tac toe board to identify the winner? var player1 = "X"; var player2 = "O"; ...

Leveraging the power of Javascript/jQuery to manipulate form

On my website, I have implemented a form that requires a customized response for certain zip codes. To achieve this, I am developing a code that validates the first 3 digits of the entered zip code against a predefined array in my system. Although the code ...

The npx create-react-app command fails to create a React app

Attempting to generate a new React application using the command npx create-react-app myapp on my computer is proving unsuccessful. Here's what I encountered: When running the command D:\AED>npx create-react-app aed, it took 52.503 seconds to in ...

Unable to change the variable for the quiz

Currently, I am in the process of developing a quiz app and I am facing an issue with my correct variable not updating. Whenever I trigger the function correctTest() by clicking on the radio button that corresponds to the correct answer, it does get execut ...

Best Practices for Managing Message Alerts in React with Material-UI

I'm currently working on a web application with React and Material UI, which includes a registration form. After submitting the registration form successfully, I want to display a success message at the top of the page. To ensure consistency across m ...

How can I return from cloud functions to Firebase Hosting?

So, here's my idea: to improve the search engine optimization (SEO) of my Single Page Application (SPA), I plan on detecting web crawlers on the server side using headers. If a crawler is detected, I want to render the page with Puppeteer and return i ...

Refresh the table every couple of seconds

I need to regularly update a table every two to three seconds or in real-time if possible. The current method I tried caused the table to flash constantly, making it difficult to read and straining on the eyes. Would jQuery and Ajax solve this issue? How c ...

The flag will never turn true; it's stuck in the false position

Currently, I am in the process of developing a custom hook to store data on a server. To mimic the server call, I have implemented a simple setTimeout function that changes the value of the data creation flag to true after 2 seconds. I have a specific fun ...

Do I have to divide the small functions in my Node.js controller into smaller ones?

When signing up users in my controller, do I need to break up the sign-up steps into individual asynchronous calls or is one big asynchronous call sufficient? Each step relies on the previous one: Validate user Create user Create group Add user to group ...

Ordering dates by week in AngularJS 1

Currently, I have a list of objects: [{ name: one, date: 2017-09-18 }, { name: two, date: 2017-09-11 }, { name: three, date: 2017-09-13 }] I am looking to organize this list by week. Perhaps like the following structure: { 1week(or , m ...

Unexpected behavior when using Async.map in conjunction with async.waterfall

Utilizing Async, I am using async.map() to connect my data array with a function and incorporating async.waterfall() within that function to execute functions in a series. However, the waterfall function is not functioning as anticipated. I have also attem ...

What is the best way to eliminate an object from an array using JavaScript?

I am currently working with two arrays named totalArray and selectionArray. These arrays have dynamic values, but for the sake of example I have provided sample arrays below. My goal is to remove objects from totalArray based on their id rather than inde ...

Is the provided code snippet considered a function-statement, function-expression, and function-expression-statement?

Currently, I am examining some code snippets from the EcmaScript.NET project. Specifically, I am delving into the definitions within FunctionNode.cs file. The comment above the definitions provides a detailed explanation of the three types of functions tha ...

Update the content of the document element by assigning it a lengthy string

I'm utilizing JQuery to dynamically assign content to a div element. The content has numerous lines with specific spacing, so this is the approach I am taking: document.getElementById('body').innerHTML = "Front-End Developer: A <br/> ...

Incorporating JSON data into an HTML table

Looking to populate an HTML table with JSON data, but struggling with parsing and appending the data correctly. Can anyone provide guidance or assistance? <!DOCTYPE html> <html> <head> <title>JSON Demo</title> < ...

An undefined variable was encountered within the 'else' statement

I am encountering an issue with my code where it is returning an 'undefined' error. The problem arises when I attempt to remove an id from an array using the variable 'id', but instead, it throws an error stating 'undefined'. ...

Swipe to modify Array

Currently, I am in the process of developing an application that features a Swipe card interface using both AngularJS and the Ionic framework. The functionality of this app will be similar to the one found at . When swiping to accept a card, I want the ar ...

I encountered an issue while attempting to build the react-create-library with Material UI

Recently, I wanted to develop my own React package using the create-react-library command. However, I ran into an issue while following the provided instructions. The error message that popped up when attempting to build my project was as follows: Error: & ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Tips for ensuring that images fully occupy my carousel slides

I am struggling to make my images fit properly within the slides. Here is the code snippet I have tried along with some screenshots: <div className="relative h-24 w-20 sm:h-44 sm:w-100 md:h-44 md:w-60 flex-shrink-0"> <Carousel showThu ...