Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lazily initialise state #7

Open
oliverjam opened this issue Sep 18, 2020 · 1 comment
Open

Lazily initialise state #7

oliverjam opened this issue Sep 18, 2020 · 1 comment

Comments

@oliverjam
Copy link

let initialRows = [];
for (let i = 0; i < height; i++) {
initialRows.push([]);
for (let k = 0; k < width; k++) {
initialRows[i].push("blank");
}
}
const randomPosition = () => {
const position = {
x: Math.floor(Math.random() * width),
y: Math.floor(Math.random() * height),
};
return position;
};
const [rows, setRows] = React.useState(initialRows);

This is more of an optimisation (your code is totally fine as is), but I think it's a cool thing to learn. useState can actually take a function that it will run to get the initial state value: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state

This lets you "lazily" initialise state, which means only running the initialisation code once, rather than on every render. E.g. your code right now has to run a bunch of for loops and build up an array every time the snake moves, even though the initialArray is only used on the very first render, to initialise the state.

@oliverjam
Copy link
Author

Oh also a cool way to create arrays of arbitrary length:

const arr = Array.from({ length: 10 });

It can also take a map function as the second argument, to pre-populate the array.

const rows = Array.from({ length: width }), () => "blank")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant