Albert Putra Purnama • 2023-01-16
I've been managing internal state of inputs wrong. Let me share why I think so.
I've been managing internal state of inputs wrong. I think I found a better way to manage internal states
If you have been following my journey, I've spent the past couple of months building forms for Typedream. I created countless inputs and learned a lot of ins and outs of the inputs. I haven't mastered it yet, but I think I found something interesting.
I wanted to make a simple input like the following, let's call it the placeholder input
Input field for a placeholder
I want this input to show different values if I pick different element in Typedream's editor. Let's say I have the following form:
2 Simple text inputs having different placeholder values
I want to show "Enter your first name" or "Enter your age" in the placeholder input above depending on which element I clicked on the Typedream editor.
My usual setup for this is usually like:
In the end I have something like
Initial solution: create internal state
I don't think this setup is generally bad, but due to the way that the input is re-rendered it causes problems whenever I select different elements. The problems is how does the input know that the element has changed? Do I need to create another useEffect
just to handle cleaning up the internal state whenever another element is picked?
Adding more state inside the input seems off and I think we can simplify this.
Let's zoom out from the inputs and remember the time when ESLint yells at us when we're using array indexes as key
. Specifically this rule.
And this ESLint rule refers to a React doc which is the usage of the key
in a react element.
Changing key tells React that the element has changed, therefore re-renders are required.
Ok so how do we use this to our advantage?
Final solution: uncontrolled input with key usage
What I did:
elementId
defaultValue
instead of value
propertyWhat this does is it allows for much cleaner implementation, removing unnecessary effects and internal state that is harder to manage.
You can see that the input's key now changes everytime elementId
changes. Which is what we want!
We no longer need to create new effect to handle element changes and reset the internal state because there's no more internal state!
Hope this helps!
Suggest new blog topics down here!
Apurn.eth
Copyright © 2022 apurn.eth. All rights reserved.
Connect with me
Legal
Terms of Servicee
Privacy Policy
Made in Typedream