Skip to content

Instantly share code, notes, and snippets.

@RenatoLopes771
Created December 22, 2021 20:47
Show Gist options
  • Save RenatoLopes771/3e33d84053de2d2f1d281a0ffdb49cfa to your computer and use it in GitHub Desktop.
Save RenatoLopes771/3e33d84053de2d2f1d281a0ffdb49cfa to your computer and use it in GitHub Desktop.
Forms without libraries and thousands of use states
// By Ben Awad
import { useState } from "react";
export function useForm(initialValues) {
const [values, setValues] = useState(initialValues);
return [
values,
(e) => {
setValues({
...values,
[e.target.name]: e.target.value
});
}
];
}
// Example
import React, { useState } from "react";
import { useForm } from "./useForm";
export default function App() {
const [values, handleChange] = useForm({ email: "", password: "" });
return (
<div>
<input name="email" value={values.email} onChange={handleChange} />
<input
type="password"
name="password"
value={values.password}
onChange={handleChange}
/>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment