'Updating React useState alongside some global state change

Consider the following:

const Foo = () => {
  let [callReqSuccess, setCallReqSuccess] = useState(false);
  const [addToNotifState] = useAddToNotifState();

  useEffect(() => {
    if (callReqSuccess) {
      addToNotifState("success", "Meeting request sent successfully");
      setCallReqSuccess(false);
    }
  }, [callReqSuccess, addToNotifState]);

  const submitForm = async (data) => {
    // ... post data
    setCallReqSuccess(true);
    // here setQueryData sets the global state
    setQueryData(someData); 
  };
  // ... rest of code
};

Upon successful form submission, I expect the local useState to be set to true.

And in the subsequent <Foo /> render, the local state callReqSuccess to be true. However, that does not happen.

Which is because, (I suspect), the code setQueryData(someData) updates the global state & React discards the local <Foo /> update?

Is my assumption correct?



Solution 1:[1]

Based on the code snippet shared, your assumption is correct.

The reason subsequent Foos do not have the global property set is because the Foo component itself initializes with false for callReqSuccess

Every new Foo created will be set to false irrespective of the global value.

I would suggest, if possible, pass the global value as the initial value of callReqSuccess when initializing the state:

const [callReqSuccess, setCallReqSuccess] = useState(yourGlobalValueVariable);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aneesh