There is also another way of doing it using setTimeout
like so:
import { useState, useEffect } from "react"
const names = [
'tony', 'elias', 'fadi'
]
export default function MyComponent() {
const [currentName, setCurrentName] = useState(names[0]);
function setRandomName() {
const index = Math.floor(Math.random() * names.length);
let newName = names[index]
if (newName == currentName) { setRandomName() }
else { setCurrentName(newName) }
return
}
useEffect(() => {
setTimeout(() => {
setRandomName()
}, 1000);
}, [currentName])
return (
<div>
<h1>name:{currentName}</h1>
</div>
)
}
Here I'm using a recursive function for setting the random name because by doing it this way if the name name is repeated on an interval then the function runs again until a new different name is set.
The actual time interval is happening within useEffect
, what I'm doing here is simply setting a timeout. This works because I'm passing currentName
as a dependency to useEffect
so the code within useEffect
will run every time currentName
changes, which will continue happening becaue every time useEffect
runs it changes the value of currentName
.
To show the simplicity of the actual time interval here's an example where we simply go through the list in order instead of randomly every second until we reach the end of the array.
import { useState, useEffect } from "react"
const names = [
'tony', 'elias', 'fadi'
]
export default function MyComponent() {
const [index, setIndex] = useState(0)
useEffect(() => {
if (index == names.length - 1) return
setTimeout(() => {
setIndex(index + 1)
}, 1000);
}, [index])
return (
<div>
<h1>name:{names[index]}</h1>
</div>
)
}
Here we use the index starting in 0 as a dependency instead and we increment it by one every time the interval runs as long as it's less than the lenght of names
.