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

JavaScript

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.

JavaScript
JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement