We all have run into this warning from React, asking us to add keys to items on a list.
Why does React ask us to do this? When using a component where we render lists, if we add, remove or change data, React can try reusing existing elements instead of recreating fresh elements.
For an in depth explaination, check out (this article)[https://legacy.reactjs.org/docs/reconciliation.html#recursing-on-children] on the Documentation site.
I want to show you another use case where this can be applied. When we are working with forms where conditional fields are present, or inputs that may be hidden due to conditions, we may need to reset the values of these inputs. To force trigger a unmount and remount of the particular component, we can use the “key” idea we have explained earlier.
In this particular form, if you try to switch between Alice and Bob, the details never change since the internal state of the component is maintained. I was running into a similar issue where I had an input component that needed to have its state reset, and using this technique was the simplest way possible.
Is this the right way? probably not. But it gets the job done. Always better to know the tools in our locker.