Is it better practice to "lift the state up" or share state setters to children?

Viewed 71

When passing data from a child component to its parent, is it better to lift the state up (Example1) or to share the state setters to children (Example2)?

The tutorials I have watched lift the state up, however, I find sharing the state setters to be simpler.

Is one better practice than the other? Are there any benefits that one has over the other?

1 Answers

Hmm, it seems like something of a false choice in those two examples. The first example is too vague to point it out, but both examples have the parent passing something to the child, so that the parent can be impacted by what the child is doing. The first example is too vague in its details to explain how that callback recieves data from the child, but it would likely receive some kind of package, not just a knock on the door.

Really, using callbacks isn't much different from using direct setters, when it comes down to it. Both situations have the parent passing a function to the child, so that the child can communicate with the parent.

Providing direct state setters is one way to do it, but it is less flexible than defining a callback contract. In a way, a simple setter is kind of like the child component inserting itself into the guts of the parent, while a callback is more like a handoff. This can lead you to name the child property based on the parent state, which keeps it from being used elsewhere or for a second, almost identical piece of state in the same parent, without the meaning of the property name beconing confusing.

With callbacks, you can more clearly define what the child needs the parent to know about. A form field, for example, needs the parent to provide a value, but rather than saying "I need a setter to update your value" it says "Give me a function so I can tell you the value's changed." It more clearly describes what's happening, rather than simply that a value is needed.

It also gives the parent the choice of what to do about the event happening. Rather than blindly updating the value, the parent might decide to format it, or to prevent the value from changing if it fails to meet criteria.

This isn't that different from standard HTML. A form field takes a value, but it doesn't simply update your Javascript. It creates an event that your Javascript listens for, and your Javascript decides what to do with it.

So, defining a callback contract might be a bit more effort, but having the callback in place will make it easier to manage complexity if logic needs to happen before the value is updated.

Related