How to update a React component's dependencies in useEffect without creating an infinite loop
P粉609866533
P粉609866533 2024-04-05 14:31:46
0
1
1404

I have a React component where I need to wait for a stored value (member) to be updated and then delete a member based on a condition before setting the stored value. However, this obviously creates a loop.

useEffect(() => {
    if(members.length > 0) {
        setMembers(members.filter((item) => item.name != 'Bob'));
    }

}, [members]);

Is there any good way to solve this problem? Based on my application setup, I really need to do this in this component.

P粉609866533
P粉609866533

reply all(1)
P粉585541766

You can try using updater state const [update, setUpdate] = useState(false) and pass update as a dependent array. When the member list is updated, use setUpdate(!update).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!