Skip to content

How to add all filtered elements in an state varaible

i have an array of objects containing users data stored in a state varaible and a table where I am displaying these users. I have a search field where a user can type name and search. Now my question is when a user types i want to search from these names and update the state variable and when user clears the input ,that time i want to show all simple terms a search functionality.

const searchUsers = () => {
    items.filter((item) => {
      if (searchTerm === null) {
        return item;
      } else if (item.title.toLowerCase().includes(searchTerm)) {


You can try useMemo hook for this. You dont even need to update the state for filtered results.

const searchResults = useMemo(() => {
  if (!searchTerm) {
    return items;

  return items?.filter((item) =>
}, [items, searchTerm]);

You can directly use the searchResults while rendering your table.