Trying to use recently set state immediately may result in nulls

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the react category.

Last Updated: 2021-05-16

I had the following code:

const { appointmentSlots, setAppointmentSlots } = useState([])

function handleLocationStep() {
      testType: "covid19-test",
      country: "germany",
      postcode: formData.location,
    .then((response) => {
      // Setting state with a hook
      // Guess what is logged at this point?

      handleStepChange("Station", 0.35);

No matter what, null was being logged, even though every external sign suggested it should have data.

The fix was just to remove the logging of the react state getter and log the actual data instead. This was because state changes in React are async and won't show up immediately.

// vs log(appointmentSlots)


State changes in React are async (e.g. setCounter) and will only show up during next render. Attempting to use those variable straight away will lead to issues.