I'm creating this countdown app where it should display a random word and then start the timer. Timer works fine but the real problem is when I uncomment the line where the new word is updated in the state.
Since the state is changed, the component re-renders. Again the state is changed causing it to rerender and so on going into an infinite loop of updating the word. I'm not getting how to solve this in an optimal way.
EDIT: The new word generation process should repeat after timer hits zero.
function App() {
const [newWord, setNewWord] = React.useState('Default');
const [time, setTime] = React.useState(6);
React.useEffect(() => {
// setNewWord(generateWord())
let intervalId = setInterval(() => {
console.log('time reduced to ', time);
if (time > 0) {
setTime(time - 1);
}
if (time === 0) {
clearInterval(intervalId);
// exitGame();
}
}, 1000);
return () => {
clearInterval(intervalId);
};
})
// Generate a new word
function generateWord() {
let words = ['yeah', 'lol', 'gotcha']
let randIndex = Math.floor(Math.random() * words.length);
return words[randIndex];
}
return (
<div>
<div> Word = {newWord} </div>
<div> Time = {time} </div>
</div>
)
}
ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>