mercredi 24 juillet 2019

Where to store state in a complex form?

Where to store the state of a complex form in react

let us consider a complex form of registering a driver and owner

the driver will have all these fields

driver = {
firstName: "xyz",
lastName: "abc",
phone: "1234",
email: "m@g.com,
licence: "xy1234"
}

And owner has the following fields

owner = {
firstName: "xyz",
lastName: "abc",
phone: "1234",
email: "m@g.com,
vehicle: "1234"
}

notice how they both have 4 inputs in common so it makes sense to create a reusable component called User, so our component heirarchy becomes

Driver User licence input

at this point if i want to make a post request on the driver data I will have to store the state in the driver and update the state of the driver whenever my inputs in the user component or the licence field changes (onChange)

The catch with this is that the The Entire Driver component re-renderes whenever a single input changes. and this creates a problem when you have a lot of nested components (since the parent re-renders all its children whenever one of them changes)

Is there a better design-pattern for this solution?

Ps. this is has been the most challenging part of React for me

Aucun commentaire:

Enregistrer un commentaire