I have a React component that I need to wait for a store value (members) to update, then remove a member if it meets a condition, and then set that store value again. However this obviously creates a loop.
useEffect(() => {
if(members.length > 0) {
setMembers(members.filter((item) => item.name != 'Bob'));
}
}, [members]);
How is a good way to get around this? The way my app is set up, I really need to do this in this component.
2
Answers
You can try an updater state
const [update, setUpdate] = useState(false)
and useupdate
as the dependency array. UsesetUpdate(!update)
when the members list updates.In your case, you need to update
members
if it meets a condition, so you can check if it satisfy the condition before set the store value again:With that, if
members
is not satisfy the condition,setMembers
doesn’t run, anduseEffect
doesn’t creates a loop