setTimeout not working properly in React?

  Kiến thức lập trình

I am trying to conditionally render a component in my app homepage component.The state variable that i used can be either be true or false and based on that the background image and some other components will change inside that component. i want to make the changes in every 7 seconds. So i need to call setState function in every 7 seconds.

My approach is like this: inside the homepage Component, I declared a setTimeout function which will call the setState function after 7 seconds. Since calling the setState function will toggle the value and will cause the home component function to be called again the setTimeout function will be execute again and will again call the setState function after 7 seconds and this will continue.Atleast thats what i thought.But it is not working like that only the first call is being made but after that the value of the state variable is not changing though the setTimeout function is being called in every 7 seconds.

initial value is false.Then it becomes true but after that nothing is heppening anymore.why?

import { useState } from "react";

export default function App() {
  return <Homepage />;
}

function Homepage() {
  const [curId, setCurId] = useState(false);

  function handleCurId() {
    setCurId((cur) => !cur);
  }

  setTimeout(handleCurId, 7000);

  return (
    <div className="home-container">
      {!curId && <IntroContainer curId={curId} />}
      {curId && <IntroContainer curId={curId} />}
    </div>
  );
}

function IntroContainer({ curId }) {
  return (
    <div
      className={`intro-container`}
      style={{
        backgroundImage: `url(${!curId ? "./bg-0.jpg" : "./bg-1.jpg"})`,
      }}
    >
      {!curId ? (
        <Intro>
          <em>Hi,</em> I am
          <br /> Md. Ishmam Zahin
        </Intro>
      ) : (
        <Intro>
          I am Full Stack
          <br />
          Web Devloper
        </Intro>
      )}
      {!curId ? (
        <Button>Download CV ⬇</Button>
      ) : (
        <Button>Go to LinkeDin</Button>
      )}
    </div>
  );
}

function Intro({ children }) {
  return <div>{children}</div>;
}

function Button({ children }) {
  return <button>{children}</button>;
}

LEAVE A COMMENT