0

I am trying to cycle loop through an array of items, when the end of the array has been reached it should go back to the first item in the array, I have the following code it's not behaving the way I would like it to, and the dom doesn't update and my approach is not working!


  const items = ["item-1", "item-2", "item-2", "item-3"];
  var count = useRef(0);

  useEffect(() => {
    setInterval(() => {
      if (count.current <= items.length) count.current = count.current++;
      else count.current = 0;
    }, 3000);
  });

  return (
    <>
      <p> {items[count]} </p>
    </>
)



1 Answer 1

1
  1. items[count] won't work because the variable count is a ref object. To access it's value you need to write count.current. So it should be items[count.current].
  2. Updating a ref object doesn't lead to a re-render, so even if you apply the fix from previous step you will only see the first item rendered.

You might want to try using useState instead:

import { useState, useEffect } from 'react';

const items = ["item-1", "item-2", "item-2", "item-3"];
function App() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        const interval = setInterval(() => {
            setCount(previousCount => previousCount + 1 );
        }, 3000);
        return () => clearInterval(interval);
    }, []);
   
    const index = count % items.length;
    return <p>{items[index]}</p>;
}

EDIT: please note that inside items array you have the same item item-2 twice. So you might want change the items array to ["item-1", "item-2", "item-3", "item-4"]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.