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

136
Views
How can i re-render using useState from inside a callback and a loop on the component

i am trying to do the game of life with react, but is just rendering once instead of several times that was supposed to. Inside handleGame has a setGrid that is what is just working once.

  const handleRules = (neighbors, grid, i, j) => {
    const next = [...grid];
    switch (true) {
      case neighbors > 3:
        next[i][j] = 0;
        break;
      case neighbors < 2:
        next[i][j] = 0;
        break;
      default:
        next[i][j] = 1;
    }
    return next;
  };

  const handleGame = () => {
    for (let row = 0; row < initialRows; row++) {
      for (let col = 0; col < initialCols; col++) {
        //  let current = gridCopy[row][col];
        let next;
        if (
          row === 0 ||
          col === 0 ||
          row === initialRows - 1 ||
          col === initialCols - 1
        ) {
          /* setGrid((current) => {
            next[row][col] = grid[row][col];
            return [...next];
          }); */
        } else {
          setGrid((current) => {
            const neighbors = handleCountNeighbors(current, row, col);
            next = handleRules(neighbors, current, row, col);
            return [...next];
          });
        }
      }
    }
  };

  const handleStart = () => {
    for (let i = 0; i <= gen; i++) {
      handleGame();
    }
  };

Can someone help me? https://codesandbox.io/s/tender-snow-gcknd?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
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!