Correct Pattern for useState + useEffect #185297
-
Select Topic AreaQuestion BodyI'm trying to create a search bar that filters a list. I have useState for the search query, but I'm not sure how to use useEffect to trigger the filtering logic without causing an infinite loop. Can someone provide a clean example?" |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
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 => 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(''); useEffect(() => { The key rule: never update a dependency inside the same effect. That’s what causes infinite loops. |
Beta Was this translation helpful? Give feedback.
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…