I am writing a version of Conway's Game of Life in React. The component's state contains the grid
describing which of the cells is alive at the current time. In each game loop, the new grid
is calculated and the state is updated with the next iteration.
It occurs to me that since setState
is asynchronous, when repeatedly calling the iterate
function with setInterval
, I am not guaranteed to be using the current version of grid
each time iterate
runs.
Is there an alternative to using setInterval
in React that would avoid any potential issues caused by setState
being asynchronous?
Here are the relevant functions that describe the game loop:
go = () => {
const { tickInterval } = this.state;
this.timerId = setInterval(this.iterate, 570 - tickInterval);
this.setState({
running: true,
});
};
iterate = () => {
const { grid, gridSize, ticks } = this.state;
const nextGrid = getNextIteration(grid, gridSize);
this.setState({
grid: nextGrid,
ticks: ticks + 1,
});
};