Search code examples
reactjsuse-effectuse-stateintersection-observer

useState not showing updated value in useEffect in React


I have a useState

const [started, setStarted] = useState(false);

then I have a function where on click it sets the setStarted to true

setStarted(true)

then I have a useEffect and in there I have an IntersectionObserver that calls a function and function has a forEach and in there I am checking for started but it is always false. I am doing console log which is showing false and also the functionality isn't working so I am sure it is false.

let options = {
      rootMargin: "0px",
      threshold: [0.5, 0.5]
    };

useEffect(() => {
  let handleStart = (entries) => {
    entries.forEach((entry) => {
      if (started) {
        //do something
      } 
      console.log("started value " + started);
    });
  };
  let observer = new IntersectionObserver(handleStart, options);

  observer.observe(currentRef.current);
}, []);

Solution

  • You need to include started as a dependency for useEffect. It should be as follow:

    useEffect(() => {
        if (started) {
          // Do something with started
        }
    }, [started])
    

    When you have an empty dependency array, the useEffect will only run when the page initially loads (mounts).