React useState not updating on first click

Viewed 14178

Why doesn't the state change on first click?

const [building, setBuilding] = useState(0);
<Button 
     title="tester"
          onPress={() => {
            setBuilding(1);
            console.log(Building);
          }}/>

The console log always returns "0" on first click, instead of expected "1". How do I fix this?

1 Answers

as state updates are async, you may see your state value updating by adding building to a useEffect dependency, thus causing it to fire whenever the value of building changes.

const [building, setBuilding] = useState(0);

  useEffect(() => {
    console.log(building);
  }, [building]);

  return (
    <button
      title="tester"
      onClick={() => {
        setBuilding(1);
      }}
    >
      test
    </button>
  );
Related