Change text at every time interval - React

Viewed 2968

I am trying to change a text (it begins automatically when the screen appears) at every time interval in react, but the problem is that, the time given isn't respected, and the text is changing at a random time interval. This is a part of my code:

const names = [
    'tony', 'elias', 'fadi'
]

const [newName, setnewName] = useState(0);

useEffect(() => {
    for (const [index, value] of names.entries()) {
        setTimeout(() => { shuffle(value) }, 5000);
    }
})

const shuffle = (value) => {
    setnewName(value);
}

And thank you!

1 Answers

Couple things here, but the main issue is the use of setTimeout in a useEffect call with no dependency array. So you're calling shuffle 5000ms after each render, which is why the updates seem to occur at random times. Additionally, the way shuffle is called looks like it will pose some issues.

You should modify your code so that the shuffle function selects a random element from the names array on its own and only call shuffle one time (you might also consider renaming shuffle to something like selectRandomName). Then change setTimeout to setInterval and only call that on mount (instead of on each render).

Here's a full example:

const names = [
    'tony', 'elias', 'fadi'
]

function MyComponent() {
    const [newName, setnewName] = useState("");

    const shuffle = useCallback(() => {
        const index = Math.floor(Math.random() * names.length);
        setnewName(names[index]);
    }, []);

    useEffect(() => {
        const intervalID = setInterval(shuffle, 5000);
        return () => clearInterval(intervalID);
    }, [shuffle])

    return(
        <Text>name:{newName}</Text>
    )
}

Note the use of useCallback here is to prevent useEffect from running on each render while also preventing linter warnings from showing up.

Related