Actions handle async state updates with pending states.
Code:
1import { useTransition } from "react";23function UpdateName() {4 const [name, setName] = useState("");5 const [isPending, startTransition] = useTransition();6 const [error, setError] = useState(null);78 const submitAction = async () => {9 startTransition(async () => {10 try {11 await updateName(name);12 } catch (err) {13 setError(err.message);14 }15 });16 };1718 return (19 <div>20 <input value={name} onChange={e => setName(e.target.value)} />21 <button onClick={submitAction} disabled={isPending}>22 {isPending ? "Updating..." : "Update"}23 </button>24 {error && <p className="error">{error}</p>}25 </div>26 );27}
Benefits: