Skip to content

Instantly share code, notes, and snippets.

@DveMac
Last active December 5, 2020 13:40
Show Gist options
  • Save DveMac/879c7dba927b4d8d8d9050097844a39a to your computer and use it in GitHub Desktop.
Save DveMac/879c7dba927b4d8d8d9050097844a39a to your computer and use it in GitHub Desktop.
// we create a Memoized functional component here, notice React.memo()
const SimpleFormField = React.memo(({ name, value, onUpdate }) => {
return <input type="text" value={value} name={name} onChange={onUpdate} />
})
const SimpleForm = () => {
const [{ name, address }, setFormState] = useState({ name: '', address: '' });
const handleSubmit = (ev) => {
ev.preventDefault();
console.log(name, address);
};
const updateField = useCallback((ev) => {
const { name, value } = ev.currentTarget;
setFormState((current) => ({ ...current, [name]: value }));
}, [setFormState]);
return (
<form onSubmit={handleSubmit}>
<SimpleFormField name={'name'} value={name} onUpdate={updateField} />
<SimpleFormField name={'address'} value={address} onUpdate={updateField} />
<input type="submit" value="Save" />
</form>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment