The Object filter is experiencing a delay with processing 10,000 items

When an API returns over 10,000 objects in the format of {firstName:'john',lastName:'Cena'}, I am faced with a performance issue. In my parent React component, I make the API call in componentDidMount and pass this object to child components.

However, when users start typing in the child component, there is noticeable lag. I attempted to resolve this by using the callback method, but the issue persists.

Parent Component

const Filters = ({validation}: any) => {
    
    const [EmployeeList, setEmployeeList] = useState<any[]>([]);

    useEffect(() => {
        //get and set
    },[])

    return (
        <>
             <Staff EmployeeList={EmployeeList}/>
        </>
    )
}

Child Components

 
const onChange = useCallback(
        (e: any) => {
            const userInput = e.currentTarget.value
            if(staffList){
                setFilteredSuggestions(staffList.filter(
                    staff =>
                        staff.firstName.toLowerCase().indexOf(userInput.toLowerCase()) > -1 
                ))
            }
            setUserInput(e.currentTarget.value)
        },
        [userInput]
    )
 

Answer №1

To optimize the code, consider using a for loop instead of filter. Although you could technically continue using filter and return false for elements after the first 20 positives, it would not be as efficient.

Here's an alternative approach:

const input = userInput.toLowerCase() // moved outside to only perform toLowerCase() once
const filtered = []
for (const staff of staffList) {
    if (staff.firstName.toLowerCase().indexOf(input) > -1 || staff.lastName.toLowerCase().indexOf(input) > -1) {
        filtered.push(staff)
        if (filtered.length >= 20) {
            break
        }
    }
}
setFilteredSuggestions(filtered)

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

How to display an object in JS format using React?

Currently, I am tackling a project that presents me with the following situation: myjson: { completeName: "my name is {this.state.myName+ " "+this.state.surname}" } component.js var Component = React.createClass({ getInitialState: function() { ...

Implementing Class-based Dependency Injection in Express

Incorporating Express into a TypeScript project has presented me with a particular scenario Here is my route file: ... import findAllUsersFactory from "src/factory/FindAllUsers"; routes.get("/users", findAllUsersFactory().handle); ... ...

Managing the React Router component as a variable

I'm currently working on integrating React-Router into an existing React app. Is there a way to use react-router to dynamically display components based on certain conditions? var displayComponent; if(this.state.displayEventComponent){ {/* ...

Placing information within a nested array with multiple levels of nesting

I'll try to keep this concise, Here is the structure of the schema... import mongoose from 'mongoose' const QuestionSchema = mongoose.Schema({ questionTitle: { type: String, required: " title"}, questionBody: { type: Stri ...

Unable to insert hyperlinks into table rows within a React application

A React function was created by me to display a table. This is how the table appears. It accepts JSON as a parameter: { "id": 1, "firstName": "Richard", "lastName": "Morrison", "number ...

Creating a dynamic hyperlink variable that updates based on user input

I am attempting to create a dynamic mailto: link that changes based on user input from a text field and button click. I have successfully achieved this without using the href attribute, but I am encountering issues when trying to set it with the href attr ...

Which method is more appropriate for my request - GET or POST? Or should I consider

Recently, I've been exploring the world of get and post methods and could use some guidance! Within my App.js file, there is a user text input field and a submit button. I have a couple of tasks in mind for handling this information: Retrieve a str ...

How can I achieve a result using a floating label in a .ts file?

I'm facing a simple issue that I can't seem to figure out. The problem is with a floating label in my HTML file, as shown below: <ion-list> <ion-item> <ion-label floating >Username</ion-la ...

Searching for columns should be at the top of an angular datatable, not at the bottom

In my Angular 7 project, I am utilizing the library found at this link. I have followed the example provided, which can be seen here. Everything is working perfectly, except for the position of the search columns. I would like the search columns to appear ...

The $route object in vue-router appears to be empty when used with single file components

I am facing an issue while using single file components with vue-router and vue-2.0. The problem I can't seem to resolve is that the this.$route object, when called from a component, always returns empty values. For example: Messages.vue <te ...

What causes the error when I use "use client" at the top of a component in Next.js?

Whenever I include "use client" at the top of my component, I encounter the following error: event - compiled client and server successfully in 2.5s (265 modules) wait - compiling... event - compiled client and server successfully in 932 ms (265 modules) ...

Developing a vanilla JavaScript web component with distinct HTML and JavaScript files

As I delve into creating vanilla JS web-components, I am exploring methods to keep the template HTML separate from the JS file, ideally in a distinct HTML file. I have examined various implementations of native JS web-component setups found notably here, ...

Having trouble removing just one element from an array in Redux. Any suggestions on how to make it work properly?

I'm currently working on creating a dynamic algorithm for removing an item from an array. Reducer: import { LOAD_PAGES, REMOVE_PAGE } from "./dynamicMenuActions"; export const initialState = { pages: [] }; export const dynamicMenuReducer = (state ...

When moving from Babel version 5.8.35 to 6.0.0, be prepared for app.js to throw a SyntaxError and encounter an unexpected token during compilation

Currently, I am in the process of enhancing my ReactJS components using webpack. However, I have encountered a hurdle while trying to transition from babel version 5 to 6. Upon attempting the upgrade, it resulted in a stack trace error within my app.js cl ...

Developing with Ionic 2 allows you to efficiently run a background service using Cordova

I am currently using Ionic 2 and I have a requirement for my app to perform certain tasks even when it is closed, similar to how Gmail continues to provide notifications all the time. After some research, I came across this documentation: https://ionicfr ...

Customize your select element's background using jQuery when the content changes

Here is a select element with different options to choose from: <select class="state"> <option value="1">Done</option> <option value="2">Closed</option> <option value="2">Open</option> <option v ...

Leverage the power of jQuery's .filter() method to pinpoint and target specific text

HTML: <p class="greeting"> hello, my name is kevin. what's yours? </p> jQuery: $("p.greeting").filter(function (){ return $this.text() === "my name is"; }).css("background", "green"); I am attempting to find and highlight the phra ...

How to extract words from a dynamic router.pathname in NextJS when only the filename is displayed instead of the full path?

I'm keeping this example as straightforward as possible, but I can add more details if needed to solve the issue Currently, I am working with dynamic routes in nextJS. My application fetches data from Twitter based on the keywords entered into the dy ...

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...

Enhance Your NestJS Application by Extending Mongoose Schemas and Overriding Parent Properties

In order to achieve the desired functionality, I have a requirement for my Class B to extend a Class A. This initial step works as intended; however, the next task at hand is overriding a property of Class A within Class B. More specifically, it is necess ...