3 ms·
> Particularly for webpages with complicated structures, we have to nest dozens of components from the inside-out, where those callback functions are passed thr
by sarreph 10y ago
> Particularly for webpages with complicated structures, we have to nest dozens of components from the inside-out, where those callback functions are passed through from parent to child components across layers and layers.
Does anyone have any tips for avoiding this extremely irritating 'props-nesting' (as I like to call it)? I'm pretty new to React, and the one thing that's bugging me about it is that in more complex UI (for example, a toolbar that independently controls a nested component), is how you can't just go through a top-level component directly; you have to go all the way up and down the chain. This gets very messy once you decide to change some of the intermediate components fundamentally.
- RonanTheGrey 10y agoThis is one of the problems that Redux solves. If you have used it, you'll understand why - the state effectively lives at that Singleton level you are talking about, and components can opt-in to subscribe to changes in the state that they are interested in (at as granular a level as you wish). Vanilla Redux is quite obtuse. I prefer Jumpstate, which makes it much more declarative. https://github.com/jumpsuit/jumpstate https://github.com/jumpsuit/jumpstate I have built some fairly sophisticated applications in React and never pass props down more than one level. Like anything else, doing this well requires discipline. The author of the article appears to be complaining that React isn't a silver bullet.
- j_jochem 10y agoOne simple technique is using JSX spread to pass all props down the component hierarchy. Another is using a state container such as redux and using its container abstraction to inject actions that mutate app state into the components they are used in.
- mfrye0 10y agoYeah there is a bit of a learning curve there. I was doing the same when I first started. It really depends on what you're trying to do, but it really comes down to storing state and data in a central location. If it's a simple component, passing the on click callback to a child that updates the parent master state is pretty straightforward. So for example selecting an item in a list and updating the active item when a list item is clicked. If it's a really deeply nested component though, that can get a bit harder. I've had some success passing simple string values via the context reference, which makes the values accessible to all the children. Another pattern I've used is having a state store similar to the flux pattern using eventemitter. I'm using this pattern a lot on thebigpicture.io for the editor page. There's two main columns in the page that are very deeply nested, so I created a separate state store and individual components are able to listen to changes from different events.