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

Why is UseEffect not getting the updated value of my state variable in ReactJS?

I am new to React and have a hard time understanding why when I call useEffect after I just set the new state on a variable, the new value is undefined. Can someone also explain why the second UseEffect hook is called twice. Is it because it’s called on initial mount, and then called when it finally changes state from the first useEffect? How can I get it to fire only once val has a defined value that was set in the first useEffect?

import React from 'react';
import {useState, useEffect} from 'react'

export function App(props) {
  const [val, setVal] = useState();
  useEffect(() => {
    setVal("hello");
  },[]);
  useEffect(() => {
    console.log("value: ", val);
  }, [val])

  return (
    <div className='App'>
    </div>
  );
}

>Solution :

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

The code is working exactly as I’d expect it to.

On (or more specifically, immediately after) the first render, both effects execute. Which:

  • queues a state update and
  • logs undefined to the console

Then when state is updated, the component re-renders. This re-render has a new state value for val, which triggers the second useEffect to execute. Which:

  • logs "hello" to the console

How can I get it to fire only once val has a defined value that was set in the first useEffect?

If you want something to happen conditionally, you’d use an if statement. For example:

useEffect(() => {
  if (val) {
    console.log("value: ", val);
  }
}, [val])

This will only log val to the console if it has a "truthy" value.

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