Thariq Shihipar
Thariq Shihipar

Reputation: 1082

React - Dealing with long chains of nested callbacks

The react way of dealing with bubbling up information from a child to a parent is via callbacks.

(sample source: react.js custom events for communicating with parent nodes.)

However this can get very cumbersome after a while, e.g.

Child = (props) => <div onClick={props.callback}/>
Parent = (props) => <Child callback={props.callback}/>
GrandParent = (props) => <Parent callback={props.callback}/>
GreatGrandParent = (props) => <GreatGrandParent callback={props.callback}/>

In this example for the GreatGrandParent to get information from the Child, we have to bubble it through the Parent and GrandParent.

This happens more often than I would have thought because React strongly recommends small components.

Note: The actual event I want to fire is not just a simple click, I realize I could just listen to the click event on the grandparent in this example, but it's more complicated. Basically just want to bubble up some data from the child to the grandparent.

Upvotes: 5

Views: 1341

Answers (1)

Krzysztof Sztompka
Krzysztof Sztompka

Reputation: 7204

The idea of small decoupled component is that developing application is more easy. When components have not any hard bindings/relationships you can simply use those components where you need without building relationship context.

But when you have situation where grand grand grand child need to inform his grand grand grand parent about something, then you have built connections which may not be to good for developing process.

In those situations I think this grand ... child should communicate with grand ... parent by store (redux) or stores (flux). Eventually by context.

Possible you have some problem with architecture and you have to a little flatten your components? I think that correct structure shouldn't have problem with bubbling up informations because only parent should be interested about its child component events. Then parent should process info and inform his parent about process result, but not just pass info from child.

For example we have:

  1. Input component & Button component
  2. Form component
  3. Page component

And now:

  • When we type something to input it informs form component about typed data.
  • But form component don't have to inform page component about it (page component is not interested about letters typed to input).
  • When user click button, then button component inform about it Form (page component is not interested about button clicking events).
  • But when form get info about button click, it validate data received from input, and submit this data to server.
  • Submit event is important to page component, therefore form sent only this info to page.

In my example we shouldn't build communication between input and page.

Upvotes: 2

Related Questions