Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

355
Views
How can I update an array using useState, with as many numbers as the ones I pass to the function?

I am trying to make an image slider that gives you n new images every time you click. I am struggling to understand how to make this piece of code dynamic so that it updates the array that takes care of the indexes as many times as the number I pass to the function (in this case 3)

  const handleIncrement = () => {
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] + 1,
      prevIndex[prevIndex.length - 1] + 2,
      prevIndex[prevIndex.length - 1] + 3,
    ]);
  };

This is the entire code

function useImageSlider(range: number = 3, length: number, steps: number = 1) {
  const [index, setIndex] = useState<number[]>(Array.from(Array(range).keys()));

  const handleDecrement = () => {
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] - 1,
      prevIndex[prevIndex.length - 1] - 2,
      prevIndex[prevIndex.length - 1] - 3,
    ]);
  };
  const handleIncrement = () => {
    index[index.length - 1] + steps + 1 >= length &&
      setIndex((prevState) => [...prevState, -1]);
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] + 1,
      prevIndex[prevIndex.length - 1] + 2,
      prevIndex[prevIndex.length - 1] + 3,
    ]);
  };
  return { length, steps, handleIncrement, handleDecrement, index };
}
export default useImageSlider;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

const handleIncrement = (range) => {
setIndex((prevIndex) => [...Array(range).keys()].map(arrIndex =>
  prevIndex[prevIndex.length - 1] + arrIndex + 1));
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!