I am developing a simple Sudoku application, but I realized my code isn't re rendering after change in state. I have initialized a 2D matrix with all null values. Then I am populating a matrix by reading my JSON File. Here when I use the setter function setValueMatrix, my code isn't re-rendering. I console logged the output in the function below the setter, here it shows the new output, but in the return function, it still shows null.
So I tried making another state Variable named setName and updating it below the setValueMatrix and the code re-renders after this!
Why is it so that my code isnt re-rendering after the setValueMatrix?
The code attached has comments next to the setter function.
import React, { useState, useEffect} from 'react';
import './App.css';
import jsonfile from './puzzle.json';
function App() {
const [valueMatrix, setValueMatrix] = useState(Array.from({length: 9},()=> Array.from({length: 9}, () => null)));
const [name, setName] = useState("0")
useEffect(() =>{
populateArray();
})
const populateArray = () => {
//console.log("JSON file:", jsonfile.sudokugrid)
//console.log("State Value Matrix:", valueMatrix)
//copying the matrix into local memory
let copymatrix = valueMatrix;
valueMatrix.map((row, rowIndex) => (
row.map((column, columnIndex) => (
copymatrix[rowIndex][columnIndex] = jsonfile.sudokugrid[rowIndex][columnIndex].value
))
))
setInitialMatrix(copymatrix);
console.log("New Val:", valueMatrix)
}
const setInitialMatrix = (copymatrix) => {
setValueMatrix(copymatrix); //This part here!! The code isnt re-rendering after this setter!
//setName("5214") //But this causes a re-render!
}
return (
<div className="App">
<div>
{
console.log(valueMatrix[4][2])
}
</div>
</div>
)
}
Changing any element or field of an element object in an array does not effect your array object. You should update it deeply.
There are some ways for it. You can have a look here.
If you need a quick way to see the difference clearly, you can also check this.