Sandbox: https://codesandbox.io/s/young-fog-cpjg15?file=/src/App.tsx
I have a React app with a table of items and a sidebar in which the user can edit the selected item. The input fields are controlled components. The values in the table should not update until the input is blurred, which is why the input uses a local value
instead of simply <input value={item[field]} />
.
Of course, value
should be initialized as item[field]
. The problem: setState
doesn't accept a dependencies array like other Hooks do, so I don't have a way to tell React the difference between the input value changing and the selected item changing (the latter of which should reset value
to newItem[field]
).
I was able to solve this by adding key={item.id}
in the parent sidebar component, which resets the lifecycle of the <Input>
component it contains. This is different from how key
is usually used, though.
Is this usage of key
okay, or is there a more idiomatic way of solving this?