skip to Main Content

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


  1. You can try an updater state const [update, setUpdate] = useState(false) and use update as the dependency array. Use setUpdate(!update) when the members list updates.

    Login or Signup to reply.
  2. 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:

    useEffect(() => {
      const filterMembers = members.filter((item) => item.name != 'Bob')
      if(members.length > 0 && filterMembers.length > 0) {
        setMembers(filterMembers);
      }
    }, [members]);
    

    With that, if members is not satisfy the condition, setMembers doesn’t run, and useEffect doesn’t creates a loop

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search