0

I have this function:

const handleSearch = (event) => {
  const currentValue = event?.target?.value;
  const filteredData = searchTable(currentValue, originalData);
  setDataToTable(filteredData);
};

I tried to use useMemo() to memoize the value of filteredData in order to not perform the function searchTable because it's slow. I tried this inside the handleSearch function:

const filteredData = useMemo(() => searchTable(currentValue, originalData), [currentValue]);

But I get the Hooks can only be called inside of the body of a function component message which is correct.

How should I use useMemo for my case?

pmiranda
  • 7,602
  • 14
  • 72
  • 155
  • 1
    [Only call hooks at the top level.](https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level) – goto Dec 27 '21 at 20:55
  • What you'd probably want instead is to memoize the `searchTable` function so that when you pass the same arguments you'll get the cached result. – goto Dec 27 '21 at 20:58
  • I thought that I was doing that, I don't get you. – pmiranda Dec 27 '21 at 21:04
  • No, you're trying to memoize the return value, not the function itself, which is what I am suggesting. – goto Dec 27 '21 at 21:07

1 Answers1

0

You must store the search query into a state variable and use useMemo with this variable to compute the filtered data.

function App() {
  const [query, setQuery] = useState();
  const filteredData = useMemo(() => searchTable(query, originalData), [query]);
  
  function handleSearch(event) {
    setQuery(event?.target?.value);
  }

  return (...)
}
Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
  • can we use 'useEffect(()=>{const filteredData = searchTable(currentValue, originalData); setDataToTable(filteredData);}, [query,originalData])' . what you gonna choose? – Jerry Dec 27 '21 at 21:20
  • `searchTable` is being inmediatly called with `originalData` undefined – pmiranda Dec 27 '21 at 21:22
  • `useMemo` was typically created for this use case so I would use it. Your solution using `useEffect` would work but you need to declare another state variable `dataToTable` – Olivier Boissé Dec 27 '21 at 21:22
  • where does `originalData` come from ? You didn't post all your code so it's difficult to guess how this variable is initialized – Olivier Boissé Dec 27 '21 at 21:24