DEV Community

Discussion on: A cure for React useState hell?

Collapse
 
wiseai profile image
Mahmoud Harmouch • Edited

Great share! However, you can also achieve the same behavior with useState using a curried function ( also with the ability to supply a function that controls state transitions ):

import { useState } from "react";

function EditCalendarEvent() {
  const [event, setEvent] = useState({
    title: "",
    description: "",
    attendees: [],
  });

  const handleChange = (prop) => (e) => {
    // Validate and transform event to ensure state is always valid
    // in a centralized way
    // ...
    setEvent({ ...event, [prop]: e.target.value });
  };

  return (
    <>
      <input
        value={event.title}
        onChange={(e) => handleChange("title")(e)}
      />
      {/* ... */}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kamtoeddy profile image
Kamto Eddy

I've done this before but slightly different

const handleChange = (prop) => (e) => {
    // Validate and transform event to ensure state is always valid
    // in a centralized way
    // ...
    setEvent(event => ({ ...event, [prop]: e.target.value }));
  };
Enter fullscreen mode Exit fullscreen mode

Just to be sure I get the most up-to-date state

Collapse
 
shareef profile image
Mohammed Nadeem Shareef

I also do in this way. Just adding a point, instead of

setEvent(event => ({ ...event, [prop]: e.target.value }));

do

setEvent(prevEvent => ({ ...prevEvent, [prop]: e.target.value }));

It's not much of a difference but you would have a better code readability.