2nd Feb 2024

Setting state in the top level of the component

Setting state directly in the body of your functional component like that will cause an infinite loop, which will crash your app. The reason is that setting state will trigger a re-render of your component, and on each render, you are setting state again.

function SomeReactComponent() {
  const [howdy, setIsHowdy] = useState(false);

  setIsHowdy(true);

  return <div>Is howdy? {howdy ? "yes" : "no"}</div>;
}