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.
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.