Skip to content

Instantly share code, notes, and snippets.

@Y4suyuki
Created January 20, 2021 03:55
Show Gist options
  • Save Y4suyuki/7415e360efc33136c69dc3957349405d to your computer and use it in GitHub Desktop.
Save Y4suyuki/7415e360efc33136c69dc3957349405d to your computer and use it in GitHub Desktop.
reseach on calling useState state update function at the top level

You can't call react usestate update function at the top level

const Card: React.FC<{name: string}> = ({ name }) => {
  const [x, setX] = React.useState(0)
  setX(9)
  return <div className="card">
    Hello {name} {x}
  </div>
}

This code lead to Too many re-renders. error. Do this.

const Card: React.FC<{name: string}> = ({ name }) => {
  const [x, setX] = React.useState(0)
  React.useEffect(() => {
    setX(9)
  })
  return <div className="card">
    Hello {name} {x}
  </div>
}

Why?

At first it looks obvious first code is lead to infinite update loop but why second one does not become infinite? useEffect set callback to be called after render. In this example, callback set state x and this update component. Updating component render the component and call callback again. This time setX set x to 9 and this is same as current state value so update stop. This is different from calling setX at top level and using useEffect. It seems useEffect check equality of state wisely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment