DEV Community

Discussion on: React - You might not need that many states!

Collapse
 
brense profile image
Rense Bakker

Or for forms, if you're just submitting the values and not displaying them anywhere else, you can use uncontrolled inputs! :D

function MyComponent(){
  const handleSubmit = useCallback((evt) => {
    evt.preventDefault()
    console.log(evt.target.elements.data1.value) // etc...
    // submit your data...
  }, [])

  return <form onSubmit="handleSubmit">
    <input name="data1" />
    <input name="data2" />
    <input name="data3" />
    <button type="submit">submit</button>
  </form>
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
noriller profile image
Bruno Noriller

Yes, but I needed an example and forms are the easiest one. =p

Collapse
 
brense profile image
Rense Bakker

Oh yes, definitely agree with the example and the point you're making! I just felt like throwing it out there as an extra gimmick, because a lot of people don't realize sometimes you don't need to use any state at all!

Collapse
 
loucyx profile image
Lou Cyx

It can be improved a little bit using FormData:

const submitHandler = event => {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);

    // You can send formData to the back-end using fetch.
    // It arrives there as an object { data1: value1, data2: value2, data3: value3 }
};

const MyComponent = () => (
    <form onSubmit={submitHandler}>
        <input name="data1" />
        <input name="data2" />
        <input name="data3" />
        <button type="submit">submit</button>
    </form>
);
Enter fullscreen mode Exit fullscreen mode

The good thing about using the platform that way, is that you can transfer that knowledge anywhere, not just React. You can literally use that same submitHandler in every library or framework out there (the philosophy that Remix has).

Cheers!

Collapse
 
rcls profile image
OssiDev

I always prefer this over controlled inputs. Less code, better performance.