useSearch Hook Logic - abhiram-shaji/Langroove GitHub Wiki
This documentation provides an overview of the useSearch
hook, which implements a reusable search functionality to filter a dataset based on user input.
The useSearch
hook:
- Maintains a search term state.
- Filters a dataset based on the search term.
- Returns the search term, its setter, and the filtered dataset.
- Manages the search term entered by the user.
-
State Variable:
-
search
: Stores the current search term.
-
-
Code Snippet:
const [search, setSearch] = useState<string>('');
-
Process:
- The
setSearch
function is used to update thesearch
term dynamically.
- The
- Filters the input dataset based on the current search term.
-
Functionality:
- Converts the
search
term and item names to lowercase for a case-insensitive match. - Filters the dataset by checking if each item's
name
includes thesearch
term.
- Converts the
-
Code Snippet:
const filteredData = data.filter((item) => item.name.toLowerCase().includes(search.toLowerCase()) );
-
Process:
- Iterates through the
data
array to filter items. - Updates the
filteredData
array dynamically as thesearch
term changes.
- Iterates through the
- Ensures reusability across datasets with different types, as long as the items include a
name
field.
-
Generic Type:
-
T
represents the type of each item in the dataset. - Extends
{ name: string }
to ensure items have aname
field.
-
-
Code Snippet:
const useSearch = <T extends { name: string }>(data: T[]): UseSearch<T> => { ... };
-
Benefits:
- Provides compile-time type checking.
- Ensures the hook works with various data structures that include a
name
field.
Property/Method | Description |
---|---|
search |
The current search term. |
setSearch(value) |
Updates the search term dynamically. |
filteredData |
The dataset filtered based on the search term. |
const items = [
{ name: 'Apple', category: 'Fruit' },
{ name: 'Banana', category: 'Fruit' },
{ name: 'Carrot', category: 'Vegetable' },
];
import useSearch from './hooks/useSearch';
const App = () => {
const { search, setSearch, filteredData } = useSearch(items);
return (
<div>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search items..."
/>
<ul>
{filteredData.map((item, index) => (
<li key={index}>{item.name}</li>
))}
</ul>
</div>
);
};
-
Empty Search Term:
- If the
search
term is empty, thefilteredData
array returns the original dataset.
- If the
-
Case Insensitivity:
- Converts both
search
term and item names to lowercase to handle case differences.
- Converts both
- The hook is generic and can be reused for any dataset that contains a
name
field, regardless of additional properties.
- For large datasets, consider optimizing filtering logic or implementing debounce to improve performance.
For additional customization, refer to the React Documentation.