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

State updates lagging behind #38

Open
oliverjam opened this issue Jul 23, 2021 · 0 comments
Open

State updates lagging behind #38

oliverjam opened this issue Jul 23, 2021 · 0 comments

Comments

@oliverjam
Copy link

growing-me/src/Palette.jsx

Lines 97 to 101 in 90aa67a

// @TODO these console logs are one click behind, but the database updates accurately - use async/await? Or getTreeData
console.log("treeLocation", props.treeLocation);
console.log("background", props.background);
console.log("growing", props.growing);
console.log("whoAround", props.whoAround);

I thought I'd try to explain why these logs are one click behind.

You have to think of each render of a component as a "snapshot" for a given set of props/state values. Each time you update a state value the component function is called again with the updated props/state values. This is the only way you can see updated state values—from the perspective of each "snapshot" the state value scoped within the function is constant.

function Counter() {
  const [count, setCount] = useState(0);
  function inc() {
    setCount(count + 1);
    console.log(count);
  }
  return <button onClick={handleClick}>{count}</button>;
}

In this example the log will always refer to the count variable as it was defined for the current render. E.g. when the page loads count is 0. You click the button, schedule a state update to change count to 1 for the next render, then log the count variable in this scope, which is still 0.

Then React processes the state update, calls the component function again and provides the updated value of count (1) to the new scope.

tl;dr if you want to log state changes do it outside of event handlers in the main component function body—this will run for every state change and should always show the updated value of each state variable:

function Counter() {
  const [count, setCount] = useState(0);
  function inc() {
    setCount(count + 1);
  }
  console.log(count);
  return <button onClick={handleClick}>{count}</button>;
}
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