I have a form with multiple text inputs. I have them all set up as controlled inputs. When typing, there is a lag of up to several seconds for the new text to display in the fie
Here is a fix I found. It sets the parent state in onBlur. Please vet this
import React, { useState } from 'react';
import MUIField from '@material-ui/core/TextField';
import _ from 'lodash';
export default (props) => {
const [value, setValue] = useState(props.defaultValue);
const prop = _.omit(props, ['onChange', 'value', 'defaultValue']);
return (
<MUIField {...prop} value={value}
onChange={e => { setValue(e.target.value); }}
onBlur={() => {
props.onChange({ target:{ value }});
}}/>);
};
Here is an example for an input pattern, Plug in or pattern for dealing with large forms in React?. The main thing is to have your input as a component that passes changes to the parent but doesn't update from the props if they are the same.
My problem was that my state object was complex and thus causing rendering issues. My solution was to manage the state of the notes in my component, then on blur update the container state.
const { data, onEdit } = props;
const { containerNotes } = data;
const [notes, setNotes] = useState('');
useEffect(
() => {
setNotes(containerNotes);
},
[containerNotes],
);
const onChangeNotes = () => ({ target: { value } }) => {
setNotes(value);
};
const onBlurNotes = (prop) => ({ target: { value } }) => {
const newData = update(data, {
[prop]: { $set: value },
});
onEdit(newData);
};
return (
<input
type="text"
placeholder="Title"
name="title"
value={notes}
onChange={onChangeNotes()}
onBlur={onBlurNotes('containerNotes')}
/>
)
Seeing as this still gets responses, thought I'd update this and close it. Calling handleChange
within onChange
would cause the entire form to rerender on every change, thereby slowing it down. If you had a simple form you could just update onBlur
instead or create individual input components so the rerender would be isolated to that one input. Personally, I use and would recommend using Formik for building forms as it abstracts this complexity for you.
I've had redux logger middleware take enough time to create this input lag. So, try disabling that as well.
Apparently React-Hook-Form
is great at minimising re-renders, and probably optimise performance. I have yet to try it though.