1

Thank you for seeing this code. please take a look

import React, { Fragment, useEffect, useState } from "react";
export default function App() {
  const [starterModal, setStarterModal] = React.useState(true);
  useEffect(() => {
    let cronInterval = setInterval(() => {
      console.log(starterModal);
    }, 4000);
    setStarterModal(false);
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox </h1>
      <h1>starterModal {starterModal ? "True" : "False"} </h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

My expected output of the state value is false. why the log print true inside setInterval

Talha Noyon
  • 824
  • 7
  • 13

1 Answers1

0

When the code const [starterModal, setStarterModal] = React.useState(true); runs, starterModal becomes a scalar value (not object). Scalar values are passed via value, meaning the value you get in you setInterval handler is stuck forever to what it was during initialisation.

calling setStarterModal would trigger render again, so your code would run again.

This article explains a solution to your case https://upmostly.com/tutorials/settimeout-in-react-components-using-hooks (see Gotcha's section)

maxbarbul
  • 1
  • 2