react usestate custom object code example

Example 1: usestate nested object

const [currentApp, setCurrentApp] = useState({
        userID: null,
        hospitalName: null, 
        hospitalID: null,
        date: null,
        time: null,
        timestamp: null,
        slots: 1,
        appointmentType: null
    })
    
const [appointmentType, setAppointmentType] =  useState({
        Granulocytes: {
            bloodType:null,
            message: null
        }
})

const handleGranChange = (e) => {
        setAppointmentType({...appointmentType, Granulocytes : {
            ...appointmentType.Granulocytes, 
            [e.target.id] : e.target.value}
        })
		setCurrentApp({ ...currentApp, ['appointmentType'] : appointmentType  })
        console.log(currentApp)
}

Example 2: when to use previous state in useState

import React, { useState } from "react";
import ReactDOM from "react-dom";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setTimeout(() => setCount(count + 1), 2000)}>
        Delayed Counter (basic)
      </button>
      <button onClick={() => setTimeout(() => setCount(x => x + 1), 2000)}>
        Delayed Counter (functional)
      </button>
      <button onClick={() => setCount(count + 1)}>Immediate Counter</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);

Tags:

Misc Example