Skip to content
Advertisement

Change placeholder text every two seconds in React

I’m trying to change the set state value every two seconds and can run in a loop but that does not seem to work with the below logic.

Excerpt from my code

 const placeholderText = ["one", "two", "three"];
  const [state, setState] = useState("");

  useEffect(() => {
    placeholderText.map((val, index) =>
      setTimeout(() => {
        setState(placeholderText[index]);
      }, 2000)
    );
  }, []);

  console.log(state);

When I try to console log the state, I get three values at a time after two seconds. How can I set the state every two seconds and run it in a loop so that it keeps changing?

I created a working example using CodeSandbox. Could anyone please help?

Advertisement

Answer

You can make use of setInterval instead of setTimeout.

Also, we can simplify the implementation in such a way that, we don’t have to store the actual text in the state, rather we can store the index. And update the same after the stipulated interval.

const {useState, useEffect} = React;

const placeholderText = ["one", "two", "three"];

const Test = () => {
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const timer = () => {
      setIndex(prevIndex => {
        if(prevIndex === placeholderText.length - 1){
          return 0;
        } 
        return prevIndex + 1;
      })
    };
    setInterval(timer, 2000);
    
    //cleanup function in order clear the interval timer
    //when the component unmounts
    return () => { clearInterval(timer); }
  }, []);

  return <p>{placeholderText[index]}</p>
}

ReactDOM.render(<Test />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>

<div id="react"></div>

Here, in the example for the simplicity I have used placeholderText outside the component. This can be passed as prop to the component and use in the component like below and use the same as dependency to the useEffect hook.

ReactDOM.render(<Test text={placeholderText}/>, document.getElementById("react"));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement