brianzinn / react-babylonjs

React for Babylon 3D engine
https://brianzinn.github.io/react-babylonjs/
821 stars 105 forks source link

Why is the useState setter failing if we are using it without a callback ? #274

Closed Xample closed 1 year ago

Xample commented 1 year ago

Hi, noob question, I followed this tutorial: https://brianzinn.github.io/react-babylonjs/guides/animation

While this works:

  const [y, setY] = useState(0)
  useBeforeRender(() => {
    setY((oldY) => oldY + 0.1)
  })

this fails (it won't update anything)

  const [y, setY] = useState(0)
  useBeforeRender(() => {
    setY(y + 0.1)
  })

While they are using the first version in the React tutorials: https://beta.reactjs.org/reference/react/useState#counter-number

Is there any reason, the callback version one is working while the first is failing ?

Xample commented 1 year ago

Okay got it, we need to explicitly provide the dependency on y if we want to use the second way.

  const [y, setY] = useState(0)
  useBeforeRender(() => {
    setY(y + 0.1)
  },undefined, undefined, undefined, [y]))