Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it a bad or good useMemo to memorize and return filtred array?

Recentrly I came across I youtube video about usememo

In the video the guy makes the statement:
"useMemo works very well when you give primitive values for props,
but it does not work so well when you give objects or arrays for props"

I’m not sure if I understood this statememt, now I’m wondering…
Is it a good Idea or bad to use useMemo to filter and return an array?
To me it looks like an expensive function that should be memorized but now
I’m not so sure.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have the following custom hook:

import { useMemo } from "react"

export function useSearch(array: any[], search: string, field: string) {
  const filteredArray = useMemo(() =>
    array.filter(entry => {
      if (search === "") return entry
      else if (entry[field].toLocaleLowerCase()
        .includes(search.toLocaleLowerCase())) return entry
    })
    , [array, search])
  return {
    filteredArray
  }
}

The first param takes the array I want to filter
The second the search string I’m inputing
and the field I wanna search by.

Is it a good Idea use useMemo to memorize this kind of function?

Thank’s in advance

>Solution :

It would be bad. The dependencies are:

[array, search]

Where array is a compound object value and search is any possible string. The number of combinations you could come up with for these two values is extremely large and therefore will memoize many values.

Beyond that, the biggest factor is that as array immutably changes, new array values are created. If the input array is [1,2,3] and then becomes [2,3], if it ever goes back to [1,2,3], it will not be the same [1,2,3] as the first, and therefore will not get memoized value.

The search is state, and array.filter(... => /* search */) is derived (computed) state. It is an anti-pattern to store derived state. This is what React calls the single source of truth.

As alternative, you may consider using a debouncing technique so that the search only happens 150ms after the user stops typing. For a query of hello, your code will memoize for [array, "h"], [array, "he"], [array, "hel"], [array, "hell"] and [array, "hello"]. The debounce technique does not use memoization but optimizes by skipping many unwanted searches.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading