Reputation: 755
I'm working on an application that includes many inputs which are all part of one large data tree.
The data looks similar to this:
data: {
input_1: "Text",
input_2: "etc",
...
input_n: "foo"
}
Each input component receives - as a prop - the key for the location of the data it is supposed to display
and modify (<InputComponent data={data['input_1']} objectKey={'input_1'} onChange={this.updateData} />
).
There is some validation that occurs inside of the component itself but basically this.onChange
is debounced and called
when changing the text.
I'm handling onChange in a way similar to this:
onChange = (newInput, objectKey) => {
const {data} = this.state;
const newData = {
...data,
[objectKey]: newInput
};
this.setState({
data: newData
});
};
I'm noticing some slowdowns and laggy behavior when updating entries. This is - at least as far as I understand it - becuase each component that is "hooked into" this data are re-rendering.
Is this a silly approach? If so, what would be a better one? It's not that bad yet but I'm anticipating this getting worse as it increases in size/complexity.
Upvotes: 4
Views: 49
Reputation: 1478
This is my approach, any criticize is welcome since I am also looking a better way to my application with a similar issue.
I would make InputComponent
as a PureComponent
with an internal state for the current input value. PureComponent
will automatically do the shallow-compare to your state
. If your InputComponent
is more complex with state
consist of arrays or deep objects, you should manually implement your shouldComponentUpdate
yourself.
The onChange
would simply update its internal state, then debounce
the call props.onChange
onChange(val) {
this.setState(val);
debounce(this.props.onChange(val));
}
With this way, the update seems smoother and after that, the parent's value is also updated accordingly without re-render and update the children InputComponent
.
Upvotes: 1