Search code examples
reactjsreact-state-management

Why is the app not re-rendering even if the state/dependency has changed


I am changing the grid as follows

const clearPath = () => {
    grid.map((row) => {
      row.map((node) => {
        if (node.isVisited) {
          //console.log(node);
          node.isVisited = false;
        }
      });
    });
    setGrid(grid);
    console.log(grid);
  };

And rendering it as follows


return (
      <div className="arena">
        {grid.map((row, i) => (
          <div key={i} className="row">
            {row.map((node, j) => {
              const { row, col, isStart, isEnd, isWall, isVisited } = node;

              return (
                <Node
                  key={j}
                  col={col}
                  row={row}
                  node={node}
                  isEnd={isEnd}
                  isStart={isStart}
                  isWall={isWall}
                  isVisited={isVisited}
                  mouseIsPressed={mouseIsPressed}
                  onMouseDown={(row, col) => {
                    handleMouseDown(row, col);
                  }}
                  onMouseEnter={(row, col) => {
                    handleMouseEnter(row, col);
                  }}
                  onMouseUp={() => handleMouseUp()}
                ></Node>
              );
            })}
          </div>
        ))}
      </div>
    );

But when I am calling the clearPath function the grid is getting updated but the app is not re-rendering? Why is that happening?


Solution

  • You're mutating the old array instead of creating a new one. Since they're reference-equal, react bails out of the render. Since the array is an array of arrays, you'll need to map those as well, and make a copy of the nodes that change.

    const clearPath = () => {
      const newGrid = grid.map((row) => {
        return row.map((node) => {
          if (node.isVisited) {
            return { ...node, isVisited: false };
          }
          return node;
        });
      });
    
      setGrid(newGrid);
    };