DEV Community

Thiago Barreto
Thiago Barreto

Posted on

React - How to load a form with the latest data

Recently I had the following situation I needed to solve:

On a page with two tabs, the first one being a form, make sure the latest form values inserted by the user show up when they come back from the second tab.

Here is the component tree:
Tree diagram with "Page" as parent and "TabBar", "FormTab" and "InfoTab" as direct children

Here is the base code (see how the form state is lost on tab change):

Solution #1: Just lift the state up

  • move useState to parent component

Here the parent state is updated on every input change.

Solution #2: Pass state to parent on unmount, load it on mount

  • Parent: add useState
  • child: keep useState + add useRef + add useEffect (useRef is needed for us to be able to get the latest state on unmount without needing to listen to its every change).

Here the parent's state is updated only once during the life of the FormTab component, when the user leaves the form tab.

Useful when you have multiple inputs/computations going on so updating the parent's state on every input change costs you a lot.


Quick tip: for professional work, try using react-hook-form. It's a great library for form-related work (validation, submit, error messages, etc.).

Top comments (2)

Collapse
 
victorleme profile image
Victor Leme de Freitas

I like it.

Straight to the point, well written.

A common problem in react, I'll help a lot of devs.

You should write every week about this kinda of challenges.

Where is the link to join in your e-mail list?

Collapse
 
thiagocbarreto profile image
Thiago Barreto

Thanks a lot!

My goal for 2023 is to write one post every week!

I don't have an email list yet, but I'll make sure you get notified once there is one 😉