Skip to content
Discussion options

You must be logged in to vote

You actually don’t need useEffect for this at all. Filtering is a derived value from your search query, so you can compute it directly during render. That avoids infinite loops completely.

const [query, setQuery] = useState('');

const filteredItems = items.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
);

If you do want to use useEffect (for example, when filtering large data or hitting an API), make sure the effect only depends on the query and doesn’t update it again:

const [query, setQuery] = useState('');
const [filteredItems, setFilteredItems] = useState(items);

useEffect(() => {
const result = items.filter(item =>
item.name.toLowerCase().includes(query.toLowerC…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by sabarivasan1239
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Code Search and Navigation Search, navigate, and understand code on GitHub Question Ask and answer questions about GitHub features and usage
2 participants