DEV Community

Discussion on: Explain lifting state up(React) Like I'm Five

Collapse
 
brandinchiu profile image
Brandin Chiu

React, like other newer web frameworks work with "Web Components" -- the idea of encapsulating common functional components of a web app into discrete blocks to be reused.

State management and encapsulation are two different programming concepts that sometimes work against each other.

Let's look at a simple example:

I want to create a PasswordField() component, which is an input field that contains the following functionality:

  • entered text is hidden from view
  • there's an icon at the end of field that if you click it reveals the text

I also want to do some form validation on this field -- specifically we want to know if the entered text matches a specific password format I've specified.

Now, when I try to use my password field, I decide to put it in a form. I only want this form to be submittable if all of the fields in the form validate successfully.

Here's where our problems start -- our validation is encapsulated in the PasswordField() component, which means my form won't know if it validates. This is obviously a problem.

"Lifting state up" in this context, would encourage me to remove my validating state (whether or not my field is valid) by making the form responsible for this state, instead of my component.

This is what we're talking about -- moving state from a child component into the parents that manage it. It makes sense in how we actually use the state, but stands opposed sometimes to the idea of encapsulation. This is one of the reasons why we have so many other state management tools we can work with.