Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Collision betwen useState interdependency and useEffect in React Hooks

I have a useEffect with dependency A and a function where something will trigger if B is true, looking like this:

const [docs, setDocs] = useState(null);
const [update, setUpdate] = useState(false);

useEffect(() => {
  if (update == true) {
    // do this
  }
}, [docs]);

In another function, i’m setting update to true, and I update docs.

const deleteDocument = (a) => {    
  const newArray = a;
  setUpdate(true);
  setDocs(newArray);

};

The problem is that the useEffect will trigger before update is actually updated, therefore not executing the inner function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Since I would like to do this the proper way (not adding a timeout), what would be the standard way of dealing with this?

>Solution :

The problem is

  setUpdate(true);
  setDocs(newArray);

Setting a state is an async function, where you cannot wait till update is set before next state change occurs.

useRef (one of many solutions)

const docs = useRef();
const [update, setUpdate] = useState(false);

useEffect(() => {
  if (update == true) {
    // do this
  // use can use "docs" here as "docs.current"
  }
}, [update]);


const deleteDocument = (a) => {    
  const newArray = a;
// set the new value of Docs. Changing 'ref' doesnot trigger a render
  docs.current = newArray;
  setUpdate(true);
};


And you can either create update to useRef or docs to useRef. Anything should work

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading